java - 在程序中得到不一致/错误的输出多线程java

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

}

最佳答案

就像其他人所说的那样,您需要确保步骤已完成执行,为此您需要调用 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());
}

应该可以正确运行

关于java - 在程序中得到不一致/错误的输出多线程java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631352/

相关文章:

java - 使用synchronized时,Java如何确定哪个线程应该继续执行?

Java + NDK加载原生库

java - Python 相当于 Java 抽象类吗?

java - 如何将 ascii 流绑定(bind)到准备好的语句

java - 如何暂停 Runnable() 对象以进行测试

c++ - 为什么投长可以解决 "warning: cast to pointer from integer of different size"?

c# - 长时间运行的线程或任务

android - 你如何循环线程?

java - 在java中使用main和junit得到不同的结果

multithreading - F#:在异步返回之前 SwitchToThreadPool 的目的