为了更深入地了解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 1! 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();
}
}
AtomicInteger
? - Brajiinc
指令,单个指令也不能保证原子性。例如,非“volatile”long
和double
字段访问无论如何都不能保证是原子性的,尽管它是由单个字节码指令执行的。 - Holger