-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWait and Notify
82 lines (67 loc) · 1.54 KB
/
Wait and Notify
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
package soccer.play;
public class Process {
private List<Integer> list=new ArrayList<>();
private static final int LOWER_LIMIT=0;
private static final int UPPER_LIMIT=5;
private static final Object lock=new Object();
private int value=0;
public void producer() throws InterruptedException{
synchronized(lock){
while(true) {
if(list.size()==UPPER_LIMIT) {
System.out.println("Waiting for removing items");
lock.wait();
}else {
System.out.println("Adding: "+value);
list.add(value++);
lock.notify();
}
Thread.sleep(500);
}
}
}
public void consumer() throws InterruptedException{
synchronized(lock){
while(true) {
if(list.size()==LOWER_LIMIT) {
value=0;
System.out.println("Waiting for Adding items");
lock.wait();
}else {
System.out.println("Removing: "+list.remove(list.size()-1));
lock.notify();
}
Thread.sleep(500);
}
}
}
}
public class League {
public static void main(String[] args) {
Process process=new Process();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
try {
process.producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
try {
process.consumer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}