/
ReentrantReadWriteLockTest.java
78 lines (67 loc) · 1.82 KB
/
ReentrantReadWriteLockTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ReentrantReadWriteLock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author HouliangQi (neuyilan@163.com)
* @description
* @since 2021-09-03 15:28
*/
public class ReentrantReadWriteLockTest {
public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
service.submit(new Runnable() {
@Override
public void run() {
getReadLock();
System.out.println("Thread=" + Thread.currentThread() + " get read lock");
// try {
// Thread.sleep(10_000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// readUnLock();
}
});
}
}
service.submit(new Runnable() {
@Override
public void run() {
getWriteLock();
System.out.println("Thread=" + Thread.currentThread() + " get write lock");
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// writeUnLock();
}
});
for (int i = 0; i < 10; i++) {
if (i % 2 == 1) {
service.submit(new Runnable() {
@Override
public void run() {
lock.readLock().lock();
}
});
}
}
}
public static void getReadLock() {
lock.readLock().lock();
}
public static void readUnLock() {
lock.readLock().unlock();
}
public static void getWriteLock() {
lock.writeLock().lock();
}
public static void writeUnLock() {
lock.writeLock().unlock();
}
}