Skip to content

Commit 203078d

Browse files
committed
解决多线程安全问题
1 parent c6549c6 commit 203078d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

thread/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@
108108
## [synchronized](src/main/java/com/cpucode/java/synchronize)
109109

110110
- [x] [多线程安全问题](src/main/java/com/cpucode/java/synchronize/ThreadDemo.java)
111+
- [x] [解决多线程安全问题](src/main/java/com/cpucode/java/synchronize/SynchronizeDemo.java)
111112

112113
- [返回文件目录](#文件目录)
113114

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.cpucode.java.synchronize;
2+
3+
/**
4+
* @author : cpucode
5+
* @date : 2021/7/26
6+
* @time : 21:56
7+
* @github : https://github.com/CPU-Code
8+
* @csdn : https://blog.csdn.net/qq_44226094
9+
*/
10+
public class SynchronizeDemo {
11+
private static int count = 0;
12+
13+
public static void inc(){
14+
synchronized (SynchronizeDemo.class){
15+
try{
16+
Thread.sleep(1);
17+
}catch (InterruptedException e){
18+
e.printStackTrace();
19+
}
20+
count++;
21+
}
22+
}
23+
public static void main(String[] args) throws InterruptedException {
24+
for(int i = 0; i < 1000; i++){
25+
new Thread(()->{
26+
SynchronizeDemo.inc();
27+
}).start();
28+
}
29+
30+
Thread.sleep(3000);
31+
System.out.println("运行结果" + count);
32+
}
33+
}

0 commit comments

Comments
 (0)