1 Star 0 Fork 0

zxj8524210/MyThreadTest

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
App8.java 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
zxj8524210 提交于 2022-01-09 10:31 +08:00 . 原子性实验
package org.example;
import java.util.concurrent.CountDownLatch;
public class App8 {
public static int num=0;
public static void main(String[] args) throws InterruptedException {
Thread[] threads=new Thread[100];
CountDownLatch latch=new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; i++) {
threads[i]=new Thread(() -> {
for (int j = 0; j < 10000; j++) {
//此处需要加上synchronized同步代码块,来保证num++的原子性(通过上锁保证原子性)
// synchronized (App8.class){
num++;
// }
}
latch.countDown();
});
}
for (Thread thread : threads) {
thread.start();
}
//此处的目的保证num数值完整,如果latch.countDown();放在线程内for循环的前面的前面,会导致latch.await();提前放开,导致输出num变量的不准确性
latch.await();
System.out.println(num);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zxj8524210/my-thread-test.git
git@gitee.com:zxj8524210/my-thread-test.git
zxj8524210
my-thread-test
MyThreadTest
master

搜索帮助