-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListProducerConsumer.java
More file actions
94 lines (81 loc) · 2.41 KB
/
LinkedListProducerConsumer.java
File metadata and controls
94 lines (81 loc) · 2.41 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
import java.util.LinkedList;
class LinkedListManager {
private LinkedList<Integer> list;
private int maxSize;
public LinkedListManager(int maxSize) {
this.maxSize = maxSize;
list = new LinkedList<>();
}
public synchronized void produce(int value) {
while (list.size() >= maxSize) {
System.out.println("List is full, producer is waiting!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(value);
System.out.println("Produced: " + value);
notifyAll();
}
public synchronized int consume() {
while (list.isEmpty()) {
System.out.println("List is empty, consumer is waiting!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int value = list.remove();
System.out.println("Consumed: " + value);
notifyAll();
return value;
}
}
class Producer implements Runnable {
private LinkedListManager manager;
public Producer(LinkedListManager manager) {
this.manager = manager;
}
@Override
public void run() {
while (true) {
int value = (int) (Math.random() * 2024) + 1;
manager.produce(value);
try {
Thread.sleep(2000); // Increased sleep time to 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private LinkedListManager manager;
public Consumer(LinkedListManager manager) {
this.manager = manager;
}
@Override
public void run() {
while (true) {
manager.consume();
try {
Thread.sleep(500); // Reduced sleep time to 0.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class LinkedListProducerConsumer {
public static void main(String[] args) {
int maxSize = 10;
LinkedListManager manager = new LinkedListManager(maxSize);
Thread producerThread = new Thread(new Producer(manager));
Thread consumerThread = new Thread(new Consumer(manager));
producerThread.start();
consumerThread.start();
}
}