Skip to content

Commit 04cc0a8

Browse files
author
laileon
committed
blocking queue
1 parent f1835c7 commit 04cc0a8

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.blankj.custom.desingn_pattern.producer;
2+
3+
import java.util.concurrent.BlockingQueue;
4+
5+
public class Consumer implements Runnable {
6+
private BlockingQueue<String> queue;
7+
private String consumer;
8+
9+
public Consumer(BlockingQueue<String> queue, String consumer) {
10+
this.queue = queue;
11+
if (null != consumer)
12+
this.consumer = consumer;
13+
else
14+
this.consumer = "null ";
15+
}
16+
17+
@Override
18+
public void run() {
19+
try {
20+
String uuid = queue.take();
21+
System.out.println(consumer + " decayed " + uuid
22+
+ " " + Thread.currentThread());
23+
} catch (InterruptedException e) {
24+
System.out.println(e.getMessage());
25+
}
26+
}
27+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.blankj.custom.desingn_pattern.producer;
2+
3+
import java.util.UUID;
4+
import java.util.concurrent.BlockingQueue;
5+
6+
public class Producer implements Runnable {
7+
private BlockingQueue<String> queue;
8+
private String produce;
9+
10+
public Producer(BlockingQueue<String> queue, String produce) {
11+
this.queue = queue;
12+
if (null != produce)
13+
this.produce = produce;
14+
else this.produce = "null ";
15+
}
16+
17+
@Override
18+
public void run() {
19+
String uuid = UUID.randomUUID().toString();
20+
try {
21+
Thread.sleep(200);//生产需要时间
22+
queue.put(produce + " : " + uuid);
23+
System.out.println("Produce \"" + produce + "\" : " + uuid + " " + Thread.currentThread());
24+
25+
} catch (InterruptedException e) {
26+
System.out.println(e.getMessage());
27+
}
28+
}
29+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.blankj.custom.desingn_pattern.producer;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.LinkedBlockingQueue;
6+
7+
public class Tester {
8+
public static void main(String[] args) {
9+
// 队列
10+
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
11+
ExecutorService service = Executors.newCachedThreadPool();
12+
for (int i = 0; i < 6; i++) {
13+
service.submit(new Consumer(queue, "X二代" + i));
14+
service.submit(new Consumer(queue, "导演" + i));
15+
}
16+
for (int i = 0; i < 6; i++) {
17+
service.submit(new Producer(queue, "黄金酒," + i));
18+
service.submit(new Producer(queue, "美女演员" + i));
19+
}
20+
service.shutdown();
21+
}
22+
}

0 commit comments

Comments
 (0)