-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaitFirstThread.java
More file actions
122 lines (117 loc) · 3.57 KB
/
WaitFirstThread.java
File metadata and controls
122 lines (117 loc) · 3.57 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/**
* 模拟Redis查询操作
*/
class Status {
private volatile int status;
/**
* 模拟Redis查询操作
*
* @return 查询结果
*/
public int getStatus() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return status;
}
public void setStatus(int status) {
/**
* 模拟Redis查询并设置key操作,可能比较耗时,所有加了sleep
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.status = status;
}
}
public class WaitFirstThread {
/**
* 第一个版本,读线程会阻塞(串行执行)
*/
public void waitOne() {
final Status status = new Status();
ReentrantLock lock = new ReentrantLock();
Runnable r = () -> {
if (status.getStatus() == 0) {
lock.lock();
try {
if (status.getStatus() == 0) {
System.out.println("查询");
status.setStatus(1);
} else {
System.out.println("直接返回1:" + status.getStatus());
}
} finally {
lock.unlock();
}
} else {
System.out.println("直接返回2:" + status.getStatus());
}
};
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 10; i++) {
executorService.submit(r);
}
executorService.shutdown();
}
/**
* 第二个版本,用while循环等待,支持读并发
*/
public void waitTwo() {
final Status status = new Status();
ReentrantLock lock = new ReentrantLock();
AtomicInteger counter = new AtomicInteger(0);
Runnable r = () -> {
counter.getAndIncrement();
if (counter.get() > 1) {
while (status.getStatus() == 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("直接返回:" + status.getStatus());
} else {
status.setStatus(1);
System.out.println("查询");
}
};
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 10; i++) {
executorService.submit(r);
}
executorService.shutdown();
}
/**
* 第三个版本,信号量控制
*/
public void waitThree() {
final Status status = new Status();
Semaphore s = new Semaphore(1);
Runnable r = () -> {
try {
s.acquire(1);
if (status.getStatus() == 0){
status.setStatus(1);
System.out.println("查询");
}
if (s.availablePermits() < 1){
s.release(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("直接返回:" + status.getStatus());
};
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 100; i++) {
executorService.submit(r);
}
executorService.shutdown();
}
}