共享模式与基于 Condition 的等待 / 通知机制实现(6)
- UID
- 1066743
|
共享模式与基于 Condition 的等待 / 通知机制实现(6)
代码示例可能大家看了我分析半天代码会有点迷糊,这里最后我贴一段我用于验证上面Condition结论的示例代码,首先建立一个Thread,我将之命名为ConditionThread:
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
| /**
* @author 五月的仓颉http://www.cnblogs.com/xrq730/p/7067904.html
*/
public class ConditionThread implements Runnable {
private Lock lock;
private Condition condition;
public ConditionThread(Lock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}
@Override
public void run() {
if ("线程0".equals(JdkUtil.getThreadName())) {
thread0Process();
} else if ("线程1".equals(JdkUtil.getThreadName())) {
thread1Process();
} else if ("线程2".equals(JdkUtil.getThreadName())) {
thread2Process();
}
}
private void thread0Process() {
try {
lock.lock();
System.out.println("线程0休息5秒");
JdkUtil.sleep(5000);
condition.signal();
System.out.println("线程0唤醒等待线程");
} finally {
lock.unlock();
}
}
private void thread1Process() {
try {
lock.lock();
System.out.println("线程1阻塞");
condition.await();
System.out.println("线程1被唤醒");
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
private void thread2Process() {
try {
System.out.println("线程2想要获取锁");
lock.lock();
System.out.println("线程2获取锁成功");
} finally {
lock.unlock();
}
}
}
|
|
|
|
|
|
|