packageprocus2;importjava.util.concurrent.locks.Condition;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;public classProduceCosumer {public static voidmain(String[] args) {/** jdk1.5提供了多线程的升级解决方法(显示的锁机制)
* 将同步synchronized替换成了显示的Lock操作----》lock() unlock()
* 将Object中的wait、notify/notifyAll 替换成了 Condition (await/signal/signalAll)
* 该对象可以 Lock.newCondition() 获取
* 一个锁可以绑定多个condition对象,避免了因同步嵌套导致死锁问题的发生。
* 释放锁的操作必须放在我们的try/finally代码块或者try..catch/finally代码块当中使用
*
* 实现了本方只唤醒对方的操作!
*
**/Resource r= newResource();
Product product= newProduct(r);
Customer customer= newCustomer(r);
Thread t1= newThread(product);
Thread t2= newThread(product);
Thread t3= newThread(customer);
Thread t4= newThread(customer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}classResource{privateString name;private int count = 1;private boolean flag = false;private Lock lock = newReentrantLock();private Condition condition_pro =lock.newCondition();private Condition condition_cus =lock.newCondition();public void set(String name) throwsInterruptedException{
lock.lock();try{while(flag){
condition_pro.await();
}this.name = name+count++;
System.out.println(Thread.currentThread().getName()+"生产者生产的..."+this.name);
flag= true;
condition_cus.signal();
}finally{
lock.unlock();
}
}public void get() throwsInterruptedException{
lock.lock();try{while(!flag){
condition_cus.await();
}
System.out.println(Thread.currentThread().getName()+"消费者消费的.........."+this.name);
flag= false;
condition_pro.signal();
}finally{
lock.unlock();
}
}
}class Product implementsRunnable{privateResource resource;publicProduct(Resource r) {this.resource =r;
}public voidrun(){while(true){try{
resource.set("【商品】");
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}class Customer implementsRunnable{privateResource resource;publicCustomer(Resource r) {this.resource =r;
}
@Overridepublic voidrun() {while(true){try{
resource.get();
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}