我有一堂课
class SynchronizedCounter {
private int i = 0;
public synchronized void increment() {
i++;
}
public synchronized void decrement() {
i--;
}
public synchronized int getValue() {
return i;
}
}
像这样使用:
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
SynchronizedCounter c = new SynchronizedCounter();
Thread d = new Thread(new D(c));
Thread e = new Thread(new E(c));
d.start();
e.start();
System.out.println(c.getValue());
}
}
其中 D 类实现如下:
class D implements Runnable {
private SynchronizedCounter counter;
D(SynchronizedCounter counter) {
this.counter = counter;
}
@Override
public void run() {
counter.increment();
}
}
E类与D类相比只有一条不同的线路
counter.decrement();
在它的运行方法中。
我希望总是打印 0,因为 SynchronisedCounter 类的方法都是同步的,但是有时我会得到 1。你能解释一下这段代码有什么问题吗?当我在 synchronized(c) 块中运行 d.start() 和 e.start() 时,它按预期工作,当我在 d.start() 和 e.join() 之后添加 d.join() 时也会发生同样的情况e.start()。