-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
64 lines (50 loc) · 1.59 KB
/
ProducerConsumer.java
File metadata and controls
64 lines (50 loc) · 1.59 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
package com.test.multithread;
public class ProducerConsumer {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Producer producer = new Producer();
Consumer consumer = new Consumer();
Runnable produceTask = ()->{
for(int i = 0; i < 500; i++) {
producer.produce();
}
System.out.println("Done producing");
};
Runnable consumeTask = () -> {
for (int i = 0; i < 500; i++) {
consumer.consume();
}
System.out.println("Done consuming");
};
Thread consumerThread = new Thread(consumeTask);
Thread producerThread = new Thread(produceTask);
consumerThread.start();
producerThread.start();
consumerThread.join();
producerThread.join();
System.out.println("Remaining task is " + count);
}
/*
* There is race condition on count and buffer
*/
static int count = 0;
static int[] buffer = new int[10];
static class Producer {
public void produce() {
while(isFull(buffer)) {}
buffer[count++] = 1;
}
}
static class Consumer {
public void consume() {
while(isEmpty(buffer)) {}
buffer[--count] = 0;
}
}
public static boolean isFull(int[] buffer2) {
return count == buffer2.length;
}
public static boolean isEmpty(int[] buffer2) {
return count == 0;
}
}