3黑马币
本帖最后由 zhoubinjian 于 2016-4-7 17:26 编辑
/*
以下代码已更正,谢谢黑友们的回复。。
*/
import java.util.concurrent.locks.*;
class Res
{
private String name;
private String sex;
boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition condition_ru = lock.newCondition();
private Condition condition_chu = lock.newCondition();
public void setNum(String name,String sex)throws InterruptedException
{
lock.lock();
try
{
while(flag)
condition_ru.await();
this.name=name;
this.sex=sex;
flag=true;
condition_chu.signal();
}
finally
{
lock.unlock();
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_chu.await();
System.out.println(name+"----"+sex);
flag=false;
condition_ru.signal();
}
finally
{
lock.unlock();
}
}
}
class Intput implements Runnable
{
private Res r;
Intput(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
try{
if(x==0)
r.setNum("zhoubin","men");
else
r.setNum("lili","women");
x=(x+1)%2;
}
catch(InterruptedException e){}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
try{
r.out();
}
catch(InterruptedException e){}
}
}
}
class Demo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Intput(r)).start();
new Thread(new Output(r)).start();
//new Thread(new Output(r)).start();
//new Thread(new Output(r)).start();
/*
Intput in=new Intput(r);
Output ou=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
*/
}
}
|
最佳答案
查看完整内容
this.name=name;
this.sex=sex;
flag=true;
condition_chu.signal();
这段代码写在while语句外面试试
|