Skip to content

Commit 7f764c1

Browse files
committed
ReentrantLock
1 parent e60372a commit 7f764c1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

thread/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
## [AQS](src/main/java/com/cpucode/java/aqs)
129129

130130
- [x] [重入锁](src/main/java/com/cpucode/java/aqs/ReentrantDemo.java)
131+
- [x] [ReentrantLock](src/main/java/com/cpucode/java/aqs/AtomicDemo.java)
131132

132133
- [返回文件目录](#文件目录)
133134

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.cpucode.java.aqs;
2+
3+
import java.util.concurrent.locks.Lock;
4+
import java.util.concurrent.locks.ReentrantLock;
5+
6+
/**
7+
* @author : cpucode
8+
* @date : 2021/7/30
9+
* @time : 15:10
10+
* @github : https://github.com/CPU-Code
11+
* @csdn : https://blog.csdn.net/qq_44226094
12+
*/
13+
public class AtomicDemo {
14+
private static int count = 0;
15+
static Lock lock = new ReentrantLock();
16+
17+
public static void main(String[] args) throws InterruptedException {
18+
for (int i = 0; i < 100; i++) {
19+
new Thread(()->{
20+
AtomicDemo.inc();
21+
}).start();
22+
}
23+
24+
Thread.sleep(2000);
25+
System.out.println("result: " + count);
26+
}
27+
28+
public static void inc(){
29+
try {
30+
lock.lock();
31+
Thread.sleep(1);
32+
count++;
33+
} catch (InterruptedException e) {
34+
e.printStackTrace();
35+
}finally {
36+
lock.unlock();
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)