Skip to content

Commit 94a8426

Browse files
committed
Day 3 Trivial use of BlockingQueue
1 parent ccc51ce commit 94a8426

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package prodcons;
2+
3+
import java.util.concurrent.ArrayBlockingQueue;
4+
import java.util.concurrent.BlockingQueue;
5+
6+
public class UseAQueue {
7+
public static void main(String[] args) {
8+
BlockingQueue<String> bqs = new ArrayBlockingQueue<>(10);
9+
Runnable r = () -> {
10+
System.out.println("worker starting");
11+
int delay = 2000 + (int)(Math.random() * 2000);
12+
try {
13+
Thread.sleep(delay);
14+
System.out.println("worker about to write message");
15+
bqs.put("DIE!");
16+
System.out.println("Message sent");
17+
} catch (InterruptedException e) {
18+
System.out.println("huh? who interrupted me!?");
19+
}
20+
System.out.println("worker finishing...");
21+
};
22+
23+
System.out.println("main about to launch worker");
24+
new Thread(r).start();
25+
System.out.println("worker launched...");
26+
try {
27+
String msg = bqs.take();
28+
System.out.println("main received message: " + msg);
29+
} catch (InterruptedException e) {
30+
System.out.println("Huh? main interrupted.");;
31+
}
32+
System.out.println("main exiting....");
33+
}
34+
}

0 commit comments

Comments
 (0)