在程序Multi -Threading java中获得不一致/错误的输出

时间:2010-09-02 21:17:26

标签: java multithreading concurrency

/*
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());
    }

}

4 个答案:

答案 0 :(得分:6)

像其他人一样,你需要确保踏板已经完成执行,为此你需要拨打join。例如

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());
}

应该正确运行

答案 1 :(得分:4)

主线程调用value()时无法控制。它会在c上获得锁定后立即运行,即使其他线程仍在运行。

如果你想等到线程完成,请在它们上面调用join()

答案 2 :(得分:1)

您正在线程完成执行之前读取该值,因此它可能与零完全不同。

答案 3 :(得分:1)

您不是在等待线程完成运行,因此结果是c的值打印在该秒的任何位置。我敢打赌,如果你尝试了1000次,有时会不是1次。

IBM有一个关于您遇到的情况的公平教程: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzahw/rzahwex3rx.htm

相关问题