0
在代碼中,線程輸出未正確同步。輸出應該是按升序排列的數字。java中的同步輸出不正確
這裏是代碼
public class Prog {
public static void main(String[] args) {
Thread a = new Thread(new Writer(), "A");
Thread b = new Thread(new Writer(), "B");
Thread c = new Thread(new Writer(), "C");
a.start();
b.start();
c.start();
}
static class Writer implements Runnable {
private static int count;
@Override
public void run() {
while (count < 5) {
show();
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
}
private synchronized void show() {
System.out.println(Thread.currentThread().getName() + ":\t" + ++count);
}
}
}
這段代碼的
一個輸出是:
B: 2
B: 4
C: 3
A: 2
B: 5
,而預期輸出是:
B: 1
B: 2
C: 3
A: 4
B: 5
我錯過了什麼?請幫忙。
這工作!你能詳細解釋我的錯誤嗎?謝謝。 – Doc
你大概知道Java同步是如何工作的嗎?我不知道哪些部分需要更深入的解釋。 – fdreger
好吧,我需要閱讀更多關於此...感謝代碼。 – Doc