java - 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 教程中复制了这个示例,我不确定我错在哪里。
解决方案
您无需等待线程完成。所以你有机会,没有,两个或只有一个线程运行,所以你的结果可能是 -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() 中删除同步,因为它不再用于任何异步进程。
推荐阅读
- html - 调整网页大小时如何防止我的 html 元素改变位置?
- typescript - 方法声明参数的自定义 ESLint/TypeScript 缩进规则
- python-3.x - 使用 numpy 确定两个矩阵之间的距离
- python - 如何将 X 定义为列值?
- python - 如何制作statsmodels vector Autoregression可以识别的年份索引?
- javascript - 反应 useState 钩子并以多步形式提交
- python - 更改不和谐机器人昵称 (discord.py)
- ios - 在支持 iOS 13.0 的同时在 iOS 14.0 中使用 @StateObject
- php - 在laravel中输入文本时如何附加?
- css - 如何使用 CSS 仅显示部分字符串