首页 > 解决方案 > Java并发同步不起作用

问题描述

并发未按预期工作。

class Counter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}


public class Main {
    public static void main(String[] args) throws InterruptedException{
        Counter counter = new Counter();
        new Thread(() -> counter.increment()).start();
        new Thread(() -> counter.decrement()).start();
        System.out.println(counter.value());
    }
}

这个打印 1 而不是 0。我从 Oracle 教程中复制了这个示例,我不确定我错在哪里。

标签: javaconcurrency

解决方案


您无需等待线程完成。所以你有机会,没有,两个或只有一个线程运行,所以你的结果可能是 -1、0 或 1。你应该使用 join() 来等待你的线程完成。

public void main(String[] args) throws InterruptedException{
    Counter counter = new Counter();
    Thread t1 = new Thread(() -> counter.increment());
    Thread t2 = new Thread(() -> counter.decrement());
    t1.start();
    t2.start();
    t1.join(); // waits for t1 to end processing
    t2.join(); // waits for t2 to end processing
    System.out.println(counter.value());
}

您还可以从 value() 中删除同步,因为它不再用于任何异步进程。


推荐阅读