-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducer.java
More file actions
63 lines (53 loc) · 1.15 KB
/
Producer.java
File metadata and controls
63 lines (53 loc) · 1.15 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
/*import java.util.concurrent.BlockingQueue;
* BlockingQueue 队列 实现生产者 消费者模式
*
*
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
while (true) {
queue.put(produce());
}
} catch (InterruptedException ex) {
// ... handle ...
ex.printStackTrace();
}
}
Object produce() {
System.out.println("我是 produce");
return "";
}
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
while (true) { consume(queue.take()); }
} catch (InterruptedException ex) {
ex.printStackTrace();
// ... handle ...
}
}
void consume(Object x) {
// ...
}
}
class Setup {
void main() {
BlockingQueue q = new SomeQueueImplementation();
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
*/