forked from CodeOpsTech/ConcurrentJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityBlockingQueueExample.java
More file actions
33 lines (30 loc) · 1.06 KB
/
Copy pathPriorityBlockingQueueExample.java
File metadata and controls
33 lines (30 loc) · 1.06 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
// Copyright: Ganesh Samarthyam, 2016; www.codeops.tech
// Illustrates the use of PriorityBlockingQueue. In this case, if there is no element available in the priority queue
// the thread calling take() method will block (i.e., wait) till another thread inserts an element
import java.util.concurrent.*;
class PriorityBlockingQueueExample {
public static void main(String []args) {
final PriorityBlockingQueue<Integer> priorityBlockingQueue
= new PriorityBlockingQueue<>();
new Thread() {
public void run() {
try {
// use take() instead of remove()
// note that take() blocks, whereas remove() doesn’t block
System.out.println("The removed element is: "
+ priorityBlockingQueue.take());
} catch(InterruptedException ie) {
// its safe to ignore this exception
ie.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
// add an element with value 10 to the priority queue
priorityBlockingQueue.add(10);
System.out.println("Successfully added an element to the queue ");
}
}.start();
}
}