Java并发显式锁和显式条件队列
1
2
3
4
5
6
7
|
Lock
lock= new ReentrantLock(); lock.lock(); try { //具体任务 } finally { lock.unlock(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<pre class = "brush:java;toolbar:false;" > public synchronized void concreteWork() { while (!condition) { try { wait(); //此时当前线程就进入了该this对象的条件队列中等候 } catch (InterruptedException
e) {
} } //具体的工作,当条件谓词成功后执行的 } //必须要保证在调用wait之前和从wait唤醒后都要对于条件谓词测试 |
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
|
package whut.usersynchrnoized; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //利用Condition和Lock来实现有界缓存 public class ConditionBoundedBuffer<T>
{ private final Lock
lock = new ReentrantLock(); private final Condition
full = lock.newCondition(); private final Condition
empty = lock.newCondition(); private final T[]
items; private int tail,
head, count; public ConditionBoundedBuffer( int size)
{ items
= (T[]) new Object[size]; } //
阻塞直到notfull public void put(T
x) throws InterruptedException
{ lock.lock(); try { while (count
== items.length) full.await(); //
满了,则要在full条件队列中等待 items[tail]
= x; if (++tail
== items.length) tail
= 0 ; ++count; empty.signal(); //
每次唤醒一个线程 } finally { lock.unlock(); } } //
阻塞直到notEmpty public T
take() throws InterruptedException
{ lock.lock(); try { while (count
== 0 ) empty.await(); //
空了,则要在empty条件队列中等待 T
x = items[tail]; items[tail]
= null ; if (++head
== items.length) head
= 0 ; --count; full.signal(); //
每次唤醒一个线程 return x; } finally { lock.unlock(); } } } |
如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
作者:分布式编程
出处:https://zthinker.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。