一楼说的没错,给你我写的recourse代码参考,用lock写的。
public class Res {
private String name;
private String sex;
private boolean flag=false;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void Set(String name,String sex) throws InterruptedException{
lock.lock();
try {
while(flag)
condition.await();
this.name = name;
this.sex = sex;
System.out.println(Thread.currentThread().getName()+"生产者");
flag =true;
condition.signalAll();
}finally{
lock.unlock();
}
}
public void show() throws InterruptedException{
lock.lock();
try {
while(!flag)
condition.await();
System.out.println("名字"+name+"性别"+sex+Thread.currentThread().getName());
flag = false;
condition.signalAll();
}finally{
lock.unlock();
}
}
} |