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