我有一個線程類,它實現了runnable和一個int計數器作爲實例變量。兩個同步方法添加和子。當我以某種方式運行我的測試課時,它幾次都會打印錯誤的結果。據我所知,當一個方法被同步時,整個對象將被鎖定以供其他線程訪問,每次我們應該得到相同的結果,這個邏輯是正確的嗎?有些情況並非如此。我錯過了什麼嗎?與java線程不一致的結果
我的機器是Windows 7,64位。
public class ThreadClass implements Runnable {
int counter = 0;
@Override
public void run() {
add();
sub();
}
public synchronized void add() {
System.out.println("ADD counter" + (counter = counter + 1));
}
public synchronized void sub() {
System.out.println("SUB counter" + (counter = counter - 1));
}
}
的TestClass
public class ThreadTest {
public static void main(String args[]) {
ThreadClass tc = new ThreadClass();
Thread tc0 = new Thread(tc);
tc0.start();
tc0.setPriority(Thread.MAX_PRIORITY);
Thread tc1 = new Thread(tc);
tc1.start();
tc1.setPriority(Thread.NORM_PRIORITY);
Thread tc2 = new Thread(tc);
tc2.start();
tc2.setPriority(Thread.MIN_PRIORITY);
}
}
結果
ADD counter1
ADD counter2
SUB counter1
SUB counter0
ADD counter1
SUB counter0
注:你可能需要做幾次試跑中產生這種矛盾。
您應該將'add'方法中的printline改爲'ADD counter',這樣可以更容易地看到發生了什麼,並且可能還會爲每個線程提供id,以便您可以看到哪個輸出來自哪個線程。 – ChrisWue 2012-01-10 22:48:17
@ChrisWue。我再次運行更新的System.out。感謝您指點。 – kosa 2012-01-10 23:01:53