標籤:
1----使用Java.util.concurrent.locks包中的lock介面取代synchronized,通過ReentrantLock這個已經實現Lock介面的類,
建立ReentrantLock對象lock(private final ReentrantLock lock = new ReentrantLock(); ) ,並通過使用這個對象中的lock()方法讓線程獲得鎖(lock.lock(););
使用unlock();在結束代碼塊塊時釋放鎖(lock.unlock();),
2----其中while(flag)解決了if(flag)存在的重複生產,使得消費者丟失對其中被覆蓋的資料(燒雞)的讀取.但是while會導致死結,會出現全部線程都被休眠的情況,此時可以將notify ()修改為notifyAll()使得程式被全部喚醒,間接實現相互喚醒,但是由於對同類線程的喚醒時沒有意義的,此時,程式的效率降低.
3---解決上一個問題的方法為:使用Java.util.concurrent.locks中的Condition介面,通過對同一個鎖建立不同的Condition執行個體,並使用不同執行個體調用其各自的await()和signal()方法實現對t0 t1和t2 t3這2組線程的凍結和喚醒管理.從而不再需要每次都全部喚醒造成的效率降低的問題.
1 /* 2 需求:生產者---->消費者 3 資源:烤鴨一隻 4 每生產一隻,就消費一zhi 5 */ 6 import java.util.concurrent.locks.*; 7 class Resource 8 { 9 private String name;10 private int count=0;11 private boolean flag=false;12 private final ReentrantLock lock = new ReentrantLock(); 13 final Condition cond1 = lock.newCondition(); 14 final Condition cond2 = lock.newCondition();15 public void make(String name)16 {17 lock.lock();18 while(flag)19 try20 {21 cond1.await();22 }23 catch (InterruptedException e)24 {25 }26 27 this.name = name;28 count++;29 flag=true;30 cond2.signal();31 System.out.println(Thread.currentThread().getName()+"生產者..."+name+count);32 lock.unlock();33 }34 public void out()35 {36 lock.lock();37 while(!flag)38 try39 {40 cond2.await();41 }42 catch (InterruptedException e)43 {44 }45 System.out.println(Thread.currentThread().getName()+"消費者......."+count);46 flag = false;47 cond1.signal();48 lock.unlock();49 }50 51 }52 class Producer implements Runnable53 {54 Resource r = new Resource();55 Producer(Resource r)56 {57 this.r = r;58 }59 public void run()60 {61 while(true)62 r.make("烤鴨");63 }64 }65 class Customer implements Runnable66 {67 Resource r = new Resource();68 Customer(Resource r)69 {70 this.r = r;71 }72 public void run()73 {74 while(true)75 r.out();76 }77 }78 class ProducerCustomer 79 {80 public static void main(String[] args) 81 {82 //建立資源類83 Resource r = new Resource();84 //建立任務對象85 Producer pro = new Producer(r);86 Customer cus = new Customer(r);87 //建立線程88 Thread t0 = new Thread(pro);89 Thread t1 = new Thread(pro);90 Thread t2 = new Thread(cus);91 Thread t3 = new Thread(cus);92 //開啟線程93 t0.start();94 t1.start();95 t2.start();96 t3.start();97 98 }99 }
java中的生產者和消費者的問題