为什么计数为0?
我先启动线程1,然后再启动线程2。计数应为2000。但是它显示计数为0。请有人用简单的术语进行解释。
public class App {
private int count = 0;
public static void main(String[] args) {
App app = new App();
app.doWork();
}
public void doWork(){
Thread t1 = new Thread(new Runnable(){
public void run(){
for(int i = 0;i < 10000;i++){
count++;
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
for(int i = 0;i < 10000;i++){
count++;
}
}
});
t1.start();
t2.start();
System.out.println("Count is: " + count);
}
}
最佳答案
在打印线程计数时,线程尚未完成执行。
为了演示,在打印出线程数之前添加Thread.sleep()
指令:
public class App {
private int count = 0;
public static void main(String[] args) throws InterruptedException {
App app = new App();
app.doWork();
}
public void doWork() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
t1.start();
t2.start();
Thread.sleep(5000);
System.out.println("Count is: " + count); // Count is: 20000
}
}
还要注意,对原语的操作不是线程安全的,并且
count++
操作不是atomic。您应该同步对count
变量的访问,或者使用AtomicInteger
或LongAdder
代替int
。就目前而言,您最终可能会得到零到20,000之间的任何计数。