java - 在我的情况下,同步关键字不能保证线程安全
问题描述
以下代码让我感到困惑,因为同步关键字不会阻止两个线程同时访问 SafeThread.value。
当我运行代码时,结果不是预期的 20000。
我还尝试使 increment() 非静态并使两个线程具有相同的 SafeThread 实例。它也没有工作。我错过了什么吗?
public class MultithreadTesting extends Thread {
public static void main(String[] args) {
MultithreadTesting thread1 = new MultithreadTesting();
MultithreadTesting thread2 = new MultithreadTesting();
thread1.start();
thread2.start();
System.out.println(SafeThread.value);
}
public void run() {
int i = 10000;
while (i > 0) {
SafeThread.increment();
i--;
}
}
}
public class SafeThread {
public static int value = 0;
public synchronized static void increment() {
value++;
}
}
解决方案
推荐阅读
- android - 除了删除应用程序之外,是否有任何 SharedPreferences 重置条件?
- outlook - Outlook:自动隐藏客户端签名
- r - 绘制保存在一系列列表中的平均栅格像素值的 XYZ 时间序列图
- node.js - 在节点js API中逐块下载大文件
- python - Open CV SIFT 创建分段错误 - 以代码 139 退出
- batch-file - 通过 BAT 最小化运行 minecraft 服务器
- python - 如何将变量传递给getattr
- sharepoint - 如何创建可在页面上的 MSTeams 中使用的 MS Teams 选项卡的链接
- ios - Bitrise:升级到 Xcode 12.3 堆栈时花费在 CocoaPods 安装步骤上的时间大幅增加
- arrays - C语言如何删除或不显示具有0值列的行