java并发-(3)生产者消费者模式

通常,线程进入临界区,却发现在某一条件满足之后才能执行。要使用一个条件对象来管理那些已经获得锁但是却不能做有用工作的线程。

Condition

使用例子
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
package com.luhc.concurrent.lock.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* created by luhuancheng on 2018/10/9
*/
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Node node = new Node(100);

Thread producer = new Thread(new Producer(lock, condition, node), "Producer-Thread");
Thread consumer = new Thread(new Consumer(lock, condition, node), "Consumer-Thread");
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}

// 作为两个线程使用的共享变量
class Node {
Integer num;

public Node(int num) {
this.num = num;
}
}

// 生产者
class Producer implements Runnable {

private Lock lock;
private Node node;
private Condition condition;

public Producer(Lock lock, Condition condition, Node node) {
this.lock = lock;
this.node = node;
this.condition = condition;
}

@Override
public void run() {
lock.lock();
try {
while (true) {
TimeUnit.SECONDS.sleep(1);
if (node.num.equals(0)) {
node.num = 100;
System.out.println(Thread.currentThread().getName() + ": 我放入了100块钱。");
// 生产数据后,唤醒等待队列中的其他线程。即Consumer-Thread
condition.signalAll();
} else {
// 拿到锁后,发现往下执行的条件不满足,调用await()进入等待队列
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

// 消费者
class Consumer implements Runnable {

private Lock lock;
private Condition condition;
private Node node;

public Consumer(Lock lock, Condition condition, Node node) {
this.lock = lock;
this.condition = condition;
this.node = node;
}

@Override
public void run() {
lock.lock();
try {
while (true) {
TimeUnit.SECONDS.sleep(1);
// 拿到锁后,发现往下执行的条件不满足,调用await()进入等待队列
if (!node.num.equals(100)) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
node.num = 0;
System.out.println(Thread.currentThread().getName() + ": 我消费了100块钱。");
try {
// 消费了数据后,唤醒等待队列中的其他线程。即Producer-Thread
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
}

}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}