因爲它總是打印出'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