Repository navigation
Expand file tree
/
Copy pathProducerConsumerExample.java
More file actions
101 lines (84 loc) · 2.46 KB
/
Copy pathProducerConsumerExample.java
File metadata and controls
101 lines (84 loc) · 2.46 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class CustomBlockingQueue {
private int[] queue;
private int size;
private int capacity;
private int front;
private int rear;
public CustomBlockingQueue(int capacity) {
this.queue = new int[capacity];
this.size = 0;
this.capacity = capacity;
this.front = 0;
this.rear = -1;
}
public synchronized void put(int item) throws InterruptedException {
while (size == capacity) {
wait();
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
System.out.println("producer: " + item);
notifyAll();
}
public synchronized int take() throws InterruptedException {
while (size == 0) {
wait();
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
System.out.println("cpmstumer: " + item);
notifyAll();
return item;
}
}
class Producer implements Runnable {
private CustomBlockingQueue queue;
public Producer(CustomBlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
queue.put(i);
for (int j = 0; j < 10; j++) {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
class Consumer implements Runnable {
private CustomBlockingQueue queue;
public Consumer(CustomBlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
int item = queue.take();
for (int j = 0; j < 5; j++) {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
public class ProducerConsumerExample {
public static void main(String[] args) {
CustomBlockingQueue queue = new CustomBlockingQueue(5);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}