-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSynchronizedNotfy.java
executable file
·60 lines (51 loc) · 1.35 KB
/
SynchronizedNotfy.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
import java.util.concurrent.TimeUnit;
public class SynchronizedNotfy {
public static void main(String[] args){
System.out.println("begin");
Object controlObject=new Object();
new ThreadNotifier(controlObject, 2000);
new ThreadListener(controlObject,500);
System.out.println("end");
}
}
class ThreadNotifier extends Thread{
private Object controlObject;
private long timeWait=0;
public ThreadNotifier(Object controlObject, int timeWait){
this.controlObject=controlObject;
this.timeWait=timeWait;
this.start();
}
@Override
public void run(){
while(true){
synchronized(this.controlObject){
System.out.println("Notifier");
this.controlObject.notify();
}
try{Thread.sleep(timeWait);}catch(Exception ex){};
}
}
}
class ThreadListener extends Thread{
private Object controlObject;
private long timeWait;
public ThreadListener(Object controlObject, int timeWait){
this.controlObject=controlObject;
this.timeWait=timeWait;
this.start();
}
@Override
public void run(){
while(true){
for(int counter=0;counter<5; counter++){
System.out.println(counter);
try{Thread.sleep(timeWait);}catch(Exception ex){};
}
synchronized(this.controlObject){
System.out.println("Wait");
try{this.controlObject.wait();}catch(Exception ex){};
}
}
}
}