在多线程java程序中获得不一致/错误的输出
您是在线程完成执行之前读取该值的,因此它可能与零有很大不同。您没有等待线程完成运行,因此结果是c的值在该秒的任何位置都被打印出来。我打赌如果你试了1000次,就会有很多次不是1次 IBM有一个关于您遇到的情况的教程:在多线程java程序中获得不一致/错误的输出,java,multithreading,concurrency,Java,Multithreading,Concurrency,您是在线程完成执行之前读取该值的,因此它可能与零有很大不同。您没有等待线程完成运行,因此结果是c的值在该秒的任何位置都被打印出来。我打赌如果你试了1000次,就会有很多次不是1次 IBM有一个关于您遇到的情况的教程: 主线程调用value()时无需控制。它将在获得c上的锁后立即运行,即使其他线程仍在运行 如果要等待线程完成,请对其调用join()。就像其他人所说的那样,您需要确保踏板已完成执行,为此,您需要调用。比如说 /* This should always produce 0 as out
主线程调用
value()
时无需控制。它将在获得c
上的锁后立即运行,即使其他线程仍在运行
如果要等待线程完成,请对其调用
join()
。就像其他人所说的那样,您需要确保踏板已完成执行,为此,您需要调用。比如说
/*
This should always produce 0 as output since all three methods increment(), decrement(), value() are thread safe(synchronized). but it is returning 1
*/
class Counter implements Runnable {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
public void run() {
try {
this.increment();
Thread.sleep(1000);
this.decrement();
Thread.sleep(1000);
this.increment();
Thread.sleep(1000);
this.decrement();
Thread.sleep(1000);
}
catch (InterruptedException e){
return;
}
}
public static void main(String args[]) throws InterruptedException {
Counter c = new Counter();
new Thread(c).start();
new Thread(c).start();
System.out.println(c.value());
}
}
这应该运行正常
public static void main(String args[]) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(c).start();
Thread t2 = new Thread(c).start();
t1.join();
t2.join();
System.out.println(c.value());
}