我正在阅读有关同步here的信息。然后我写了这个程序
public class Counter {
int i = 0;
public synchronized void increment() {
System.out.println("inc called");
i++;
System.out.println("inc exited");
}
public synchronized void decrement() {
System.out.println("dec called");
i--;
System.out.println("dec exited");
}
public synchronized void print(String name) {
System.out.println(name + " " + i);
}
}
public class UnsynchronizedCounterTest implements Runnable {
private Counter counter = new Counter();
public UnsynchronizedCounterTest(String name) {
Thread t = new Thread(this, name);
t.start();
}
public static void main(String[] args) {
UnsynchronizedCounterTest test = new UnsynchronizedCounterTest(
"New Thread 1");
test.callMe();
}
public void callMe() {
counter.decrement();
counter.print("main thread");
}
@Override
public void run() {
counter.increment();
counter.print("another thread");
}
}
当我运行该程序时,我得到以下输出
dec called
dec exited
inc called
inc exited
another thread 0
main thread 0
dec called
dec exited
main thread -1
inc called
inc exited
another thread 0
我相信第一个输出是错误的。我不知道我的程序出了什么问题。谁能纠正我。
最佳答案
以下代码:
counter.decrement();
counter.print("main thread");
是危险的。尽管它以99%的比率显示正确的
Counter.i
值,但有时另一个线程可能会楔入第一个和第二个方法调用之间的间隙。更好地在减量和增量方法中打印值。如果只想打印而不更改值,则可以使用同步方法或块,以避免打印过时的值。输出与您的程序相对应-如果您认为它们是错误的,那么您的程序也是错误的。请解释您想要什么。