-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaitNotifyDemo.java
More file actions
61 lines (55 loc) · 1.21 KB
/
Copy pathWaitNotifyDemo.java
File metadata and controls
61 lines (55 loc) · 1.21 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
public class WaitNotifyDemo{
public static void main(String[] args){
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name, String sex){
if(flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"....."+sex);
flag = false;
this.notify();
}
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
@Override
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("Tom", "man");
else
r.set("Kate", "woman");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}