多態鎖

  有多個生產者和多消費者的時候

          問題1: 會同時生產多個或者同時消費多個,達不到生產一隻就消費一隻的目的
          原因 : 當前任務下的線程再次喚醒後沒有繼續判斷標記
          辦法 : 在線程進入判斷標記 碰到wait後,再次喚醒還要繼續判斷標記  
          將if改成while  

  問題2 : 將if改成while後 ,線程死鎖了..

          原因 : 線程每次喚醒了同一任務下的線程,就產生死鎖
          辦法 : 將線程池中等待的線程全部喚醒
          notify --> notifyAll(); 

 更好的來優化 多生產者和多消費者的問題(JAVA當中的多態鎖)
          * Java 提供了一個多態鎖 ReentrantLock(可重入的互斥鎖)

支持Condition對象 監視器當前的環境對象

          Condition提供了三個方法
          await()           ----->   wait
          signal()          ----->   notify()
          signalAll()       ----->   notifyAll() 


          try 
          嘗試着執行一段代碼,在使用資源(做數據庫的操作,對流的操作...)
          catch 
          抓去異常,解決問題
          finally
          必須執行的 釋放資源(關閉數據庫連接,關閉ResultSet.關閉流對象..) 

多消費者多生產者多態鎖運用
class KFC {

Lock lock = new ReentrantLock();
//創建倆個監視器
Condition chiefCon = lock.newCondition();
Condition customerCon = lock.newCondition();

private String foodName;
private int count;//數量
private boolean flag = false;

/**
 * 生產食物
 */
public void put(String foodName){//
    lock.lock();//鎖上了
    try{
        while(flag)
            try {chiefCon.await();} catch (InterruptedException e) {}
        count++;
        this.foodName = "第" + count +"份"+ foodName;
        System.out.println(Thread.currentThread().getName() + "生產了" + this.foodName);

        flag = true;
        customerCon.signal();
    }finally{
        lock.unlock();//釋放鎖
    }
}

/**
 * 消費食物
 */
public  void take(){
    lock.lock();
    try{
        while(!flag)
            try {customerCon.await();} catch (InterruptedException e) {}

        System.out.println(Thread.currentThread().getName() + "...消費了" + foodName);

        flag = false;
        chiefCon.signal();
    }finally{
        lock.unlock();
    }
}

}

class Chief implements Runnable{
private KFC kfc;

public Chief(KFC kfc) {
    this.kfc = kfc;
}

@Override
public void run() {
    while(true){
        kfc.put("XX烤翅");
    }
}

}

class Customer implements Runnable{

private KFC kfc;

public Customer(KFC kfc) {
    this.kfc = kfc;
}

@Override
public void run() {
    while(true){
        kfc.take();
    }
}

}

/**
* 有多個生產者和多消費者的時候
*
* 問題1: 會同時生產多個或者同時消費多個,達不到生產一隻就消費一隻的目的
* 原因 : 當前任務下的線程再次喚醒後沒有繼續判斷標記
* 辦法 : 在線程進入判斷標記 碰到wait後,再次喚醒還要繼續判斷標記
* 將if改成while
*
* 問題2 : 將if改成while後 ,線程死鎖了..
* 原因 : 線程每次喚醒了同一任務下的線程,就產生死鎖
* 辦法 : 將線程池中等待的線程全部喚醒
* notify –> notifyAll();
*
* 更好的來優化 多生產者和多消費者的問題
*
* java中的多態鎖..
*
* @author Administrator
*
*/

public class KFCTest2{

public static void main(String[] args) {
    KFC kfc = new KFC();

    Chief chief1 = new Chief(kfc);
    Chief chief2 = new Chief(kfc);

    Customer customer1 = new Customer(kfc);
    Customer customer2 = new Customer(kfc);

    Thread t1 = new Thread(chief1);
    Thread t2 = new Thread(chief2);

    Thread t3 = new Thread(customer1);
    Thread t4 = new Thread(customer2);

    t1.start();
    t2.start();
    t3.start();
    t4.start();
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章