class Res{
private String name;
private String sex;
private boolean flag=false;//Res里是否有资源
public synchronized void setInfo(String name,String sex) {
if(flag)
try {
this.wait();//Res对象作为锁旗标,wait()方法释放所占资源,同时释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name=name;
this.sex=sex;
flag=true;
this.notify();//唤醒getInfo()的线程
}
public synchronized void getInfo(){
if(!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"......"+sex);
flag=false;
this.notify();//唤醒setInfo()的线程
}
}
class Input implements Runnable{
private Res r;
public Input(Res r) {
this.r=r;
}
@Override
public void run() {
int x=0;
while(true){
if(x==0)
r.setInfo("mike", "man");
else {
r.setInfo("丽丽", "女");
}
x=(x+1)%2;
}
}
}
class Output implements Runnable{
private Res r;
public Output(Res r) {
this.r=r;
}
@Override
public void run() {
while(true){
r.getInfo();
}
}
}
public class InputOutputDemo {
public static void main(String[] args) {
Res rs=new Res();
Input in=new Input(rs);
Output out=new Output(rs);
new Thread(in).start();
new Thread(out).start();
}
}
这是一个生产,一个消费线程的例子
利用等待唤醒机制实现线程间的通信
最新推荐文章于 2019-08-21 23:45:07 发布