因为它总是打印出'3'。不需要同步?我正在测试这个简单的事情,因为我在一个真正的多线程问题中遇到了麻烦,因为它很大,所以不能很好地说明问题。这是展示这种情况的简化版本。为什么这个线程安全?
class Test {
public static int count = 0;
class CountThread extends Thread {
public void run()
{
count++;
}
}
public void add(){
CountThread a = new CountThread();
CountThread b = new CountThread();
CountThread c = new CountThread();
a.start();
b.start();
c.start();
try {
a.join();
b.join();
c.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Test test = new Test();
System.out.println("START = " + Test.count);
test.add();
System.out.println("END: Account balance = " + Test.count);
}
围绕'main'代码循环,你会发现情况并非如此。 – Chan