package procus2; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ProduceCosumer { public static void main(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 = new Resource(); Product product = new Product(r); Customer customer = new Customer(r); Thread t1 = new Thread(product); Thread t2 = new Thread(product); Thread t3 = new Thread(customer); Thread t4 = new Thread(customer); t1.start(); t2.start(); t3.start(); t4.start(); } } class Resource{ private String name; private int count = 1; private boolean flag = false; private Lock lock = new ReentrantLock(); private Condition condition_pro = lock.newCondition(); private Condition condition_cus = lock.newCondition(); public void set(String name) throws InterruptedException{ 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() throws InterruptedException{ 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 implements Runnable{ private Resource resource; public Product(Resource r) { this.resource = r; } public void run(){ while(true){ try { resource.set("【商品】"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Customer implements Runnable{ private Resource resource; public Customer(Resource r) { this.resource = r; } @Override public void run() { while(true){ try { resource.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }