为什么i++
在Java中不是原子的?
为了更深入地了解Java,我尝试计算线程中的循环执行的频率。
所以我用了
private static int total = 0;
在主要班级。
我有两个线程。
- 线程1:打印
System.out.println("Hello from Thread 1!");
- 线程2:打印
System.out.println("Hello from Thread 2!");
我计算了线程1和线程2打印的行数,但是线程1的行+线程2的行数与打印出的行总数不匹配。
这是我的代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
private static int total = 0;
private static int countT1 = 0;
private static int countT2 = 0;
private boolean run = true;
public Test() {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
newCachedThreadPool.execute(t1);
newCachedThreadPool.execute(t2);
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
run = false;
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println((countT1 + countT2 + " == " + total));
}
private Runnable t1 = new Runnable() {
@Override
public void run() {
while (run) {
total++;
countT1++;
System.out.println("Hello #" + countT1 + " from Thread 2! Total hello: " + total);
}
}
};
private Runnable t2 = new Runnable() {
@Override
public void run() {
while (run) {
total++;
countT2++;
System.out.println("Hello #" + countT2 + " from Thread 2! Total hello: " + total);
}
}
};
public static void main(String[] args) {
new Test();
}
}
iinc
用于递增整数的操作,但是仅适用于不关心并发性的局部变量。对于字段,编译器将分别生成读取-修改-写入命令。
iinc
针对字段的指令,拥有一条指令也不能保证原子性,例如,非访问volatile
long
和double
字段访问都不能保证是原子性的,无论它是由一条字节码指令执行的事实。
AtomicInteger
?