-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducerConsumerThreads.java
90 lines (86 loc) · 2.08 KB
/
ProducerConsumerThreads.java
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
package producerconsumerthreads;
import java.util.*;
public class ProducerConsumerThreads {
public static void main(String[] args) {
ArrayList<Integer> b = new ArrayList<Integer>();
Thread ob1 = new Thread(new Producer(b));
Thread ob2 = new Thread(new Consumer(b));
ob1.start();
ob2.start();
}
}
class Producer implements Runnable
{
List<Integer> b = null;
final int maxsize=5;
int i = 0;
Producer(List<Integer> b)
{
this.b = b;
}
public void produce(int i) throws InterruptedException
{
synchronized(b)
{
while(b.size()==maxsize)
{
System.out.println("Producer Waiting");
b.wait();
}
}
synchronized(b)
{
b.add(i);
System.out.println("Producing...");
Thread.sleep(1000);
b.notify();
}
}
public void run()
{
while(true)
{
i++;
try {
produce(i);
} catch (InterruptedException ex) {
}
}
}
}
class Consumer implements Runnable
{
List<Integer> b;
Consumer(List<Integer> b)
{
this.b = b;
}
public void consume() throws InterruptedException
{
synchronized(b)
{
while(b.isEmpty())
{
System.out.println("Consumer Waiting");
b.wait();
}
}
synchronized(b)
{
b.remove(0);
System.out.println("Consuming...");
Thread.sleep(1000);
b.notify();
}
}
public void run()
{
while(true)
{
try {
consume();
} catch (InterruptedException ex) {
}
}
}
}