-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncQueue.java
More file actions
72 lines (60 loc) · 1.76 KB
/
SyncQueue.java
File metadata and controls
72 lines (60 loc) · 1.76 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
64
65
66
67
68
69
70
71
72
import java.util.concurrent.SynchronousQueue;
class Producer extends Thread {
SynchronousQueue<String> sq;
String data;
Producer(SynchronousQueue<String> sq, String data){
this.sq=sq;
this.data=data;
setName("PRODUCER:"+data);
}
public void run() {
System.out.println(this.getName()+" :: Producer::run() : Starting ");
try {
int i=0;
while(i<20){
String data=new Integer(i).toString();
if(!sq.contains(data)){
System.out.println(this.getName()+" :: adding ... "+i);
sq.put(data);
}
else{
System.out.println(this.getName()+" :: ======= NOT adding "+i+". ALREADY PRESENT");
}
i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread{
SynchronousQueue<String> sq;
Consumer(SynchronousQueue<String> sq){
this.sq=sq;
setName("CONSUMER");
}
public void run() {
System.out.println(this.getName()+" :: Consumer::run() : Starting ");
try {
while(true){
System.out.println(" ------- "+this.getName()+" :: "+sq.take());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class SyncQueue {
public static void main(String... args) {
SynchronousQueue<String> sq = new SynchronousQueue<String>(true);
System.out.println("main() : Starting ");
new Consumer(sq).start();
new Producer(sq,"A").start();
new Producer(sq,"B").start();
new Producer(sq,"C").start();
new Producer(sq,"D").start();
new Producer(sq,"E").start();
new Producer(sq,"F").start();
System.out.println("main() : End ");
}
}