class resource_1{
String name;
String sex;
boolean b=false;
}
class input_1 implements Runnable{
resource_1 r;
input_1(resource_1 r){
this.r=r;
}
public void run(){
int x=0;
while(true){
synchronized(r){
if(r.b){
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(x==0){
r.name="丽丽";
r.sex="女";
}else{
r.name="旺财";
r.sex="男";
}
}
r.b=true;
r.notify();
}
x=(x+1)%2;
}
}
}
class output_1 implements Runnable{
resource_1 r;
output_1(resource_1 r){
this.r=r;
}
public void run(){
while(true){
synchronized(r){
if(!r.b){
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(r.name+"....."+r.sex);
}
r.b=false;
r.notify();
}
}
}
}
public class 等待唤醒机制 {
public static void main(String[] args){
resource_1 r=new resource_1();
input_1 in=new input_1(r);
output_1 out=new output_1(r);
Thread t=new Thread(in);
Thread t1=new Thread(out);
t.start();
t1.start();
}
} |
|