Repository navigation
Expand file tree
/
Copy pathPS23.java
More file actions
73 lines (69 loc) · 1.45 KB
/
Copy pathPS23.java
File metadata and controls
73 lines (69 loc) · 1.45 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
import java.util.LinkedList;
import java.util.Queue;
class Buffer {
private Queue<Integer> queue;
private int maxSize;
public Buffer(int maxSize) {
this.maxSize = maxSize;
this.queue = new LinkedList<>();
}
public synchronized void produce(int item) throws InterruptedException {
while (queue.size() == maxSize) {
wait();
}
queue.add(item);
System.out.println("Produced: " + item);
notify();
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
int item = queue.poll();
System.out.println("Consumed: " + item);
notify();
}
}
class Producer implements Runnable {
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
buffer.produce(i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Consumer implements Runnable {
private Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
int item = buffer.consume();
Thread.sleep(1500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class Main {
public static void main(String[] args) {
Buffer buffer = new Buffer(3);
Thread producerThread = new Thread(new Producer(buffer));
Thread consumerThread = new Thread(new Consumer(buffer));
producerThread.start();
consumerThread.start();
}
}