本帖最后由 Super_Class 于 2013-6-21 00:02 编辑
使用wait() ,notify()方法能运行,改成用Lock的方法不能运行,帮忙看看哪里的错
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Resouse {
private String name;
private int id = 1;
boolean flag = false;
Lock lock = new ReentrantLock();
Condition con_pro = lock.newCondition();
Condition con_con = lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try {
while(flag){
con_pro.await();
this.name = name + "--" + id++;
System.out.println(Thread.currentThread().getName() + "生产者" + this.name );
this.flag = true;
con_con.signal();
}
}finally{
lock.unlock();
}
}
public void con() throws InterruptedException{
lock.lock();
try {
while(!flag){
con_con.await();
System.out.println(Thread.currentThread().getName() + "消费者" + this.name);
this.flag = false;
con_pro.signal();
}
}finally{
lock.unlock();
}
}
}
|