forked from Beerkay/JavaMultiThreading
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
54 lines (42 loc) · 1.39 KB
/
ProducerConsumer.java
File metadata and controls
54 lines (42 loc) · 1.39 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
import java.util.Base64;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumer {
private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
try {
producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(()->{
consumer();
});
t1.start();
t2.start();
// Thread.sleep(30000);
}
private static void producer() throws InterruptedException {
Random random = new Random();
while (true) {//loop indefinitely
queue.put(random.nextInt(100));//if queue is full (10) waits
}
}
private static void consumer(){
Random random = new Random();
while (true) {
try {
Thread.sleep(100);
if (random.nextInt(10) == 0) {
Integer value = queue.take();//if queue is empty waits
System.out.println("Taken value: " + value + "; Queue size is: " + queue.size());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}