Input类负责输入,Output类负责输出。每输入一次 就要输出一次。Resouce是锁对象。
public class Input implements Runnable{private Resouce res;
Input(Resouce res){
this.res=res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x=0;//用来控制将名称性别设置
while(true){
synchronized(res){
if(res.flag){
try{
res.wait();
}catch(Exception e){}
}
if(x==0){
res.name="隔壁老王";
res.sex="男";
}else{
res.name="roes";
res.sex="male";
}
x=(x+1)%2;
res.flag=true;
res.notify();
}
}
}
}
class Output implements Runnable{
private Resouce res;
Output(Resouce res){
this.res=res;
}
@Override
public void run() {
while(true){
synchronized(res){
if(!res.flag){
try{
res.wait();
}catch(Exception e){
}
}
System.out.println(res.name+"-----"+res.sex);
res.flag=false;
res.notify();
}
}
}
}
public class Resouce {
String name ;
String sex;
boolean flag=false;//此标志为false表明输入完毕,为true表明输出完毕
}
class Main{
public static void main(String[] args){
Resouce res=new Resouce();
Input in=new Input(res);
Output out=new Output(res);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}