java多線程-經典生產者消費者問題

問題:

寫一個固定容量同步容器,擁有put和get方法,以及getCount方法,能夠支持2個生產者線程以及5個消費者線程的阻塞調用。

方案一:

1.使用synchronized、notifyAll、wait實現

public class PSproblem_01<T> {
    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10; //最多10個元素
    //生產過程
    public synchronized void put(T t) {
        while (lists.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lists.add(t);
        System.out.println("生產者" + Thread.currentThread().getName() + "生產了" + t);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll();
    }
	//消費過程
    public synchronized T get() {
        T t = null;
        while (lists.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = lists.remove();
        System.out.println("消費者" + Thread.currentThread().getName() + "消費了" + t);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll();
        return t;
    }


    public static void main(String[] args) {
        PSproblem_01<String> container = new PSproblem_01<>();

        //啓動2個生產者線程
        for (int i = 1; i <= 2; i++) {
            int index = i;
            new Thread(() -> {
                int count = 0;
                while (count++ < 5) {
                    container.put("包子");
                }
            }, Integer.toString(index)).start();
        }
        //啓動5個消費者線程
        for (int i = 1; i <= 5; i++) {
            int index = i;
            new Thread(() -> {
                int count = 0;
                while (count++ < 2) {
                    container.get();
                }
            }, Integer.toString(index)).start();
        }
    }
}

3.疑問
爲什麼判斷條件用while而不用if?
先來了解一下兩個概念,以便更容易理解問題答案。

  • 鎖池:
    假設線程A已經擁有了某個對象的鎖,而其它的線程想要調用這個對象的某個synchronized方法(或者synchronized塊),由於這些線程在進入對象的synchronized方法之前必須先獲得該對象的鎖的擁有權,但是該對象的鎖目前正被線程A擁有,所以這些線程就進入了該對象的鎖池中。
  • 等待池:
    假設一個線程A調用了某個對象的wait()方法,線程A就會釋放該對象的鎖後,進入 到了該對象的等待池中。
  • 當有線程調用了對象的notifyAll()方法(喚醒所有wait線程)或notify()方法(只隨機喚醒一個wait線程),被喚醒的的線程便會進入該對象的鎖池中,鎖池中的線程會去競爭該對象鎖。也就是說,調用了notify後只要一個線程會由等待池進入鎖池,而notifyAll會將該對象等待池內的所有線程移動到鎖池中,等待鎖競爭

假設我們遇到這樣情況:
生產者線程1獲取鎖後,容器容量判斷已經到達MAX,所以線程1執行wait()後進入釋放當前對像鎖,進入等待池中。隨後又一個生產者線程2獲得鎖,由於容量還是MAX,所以線程2也釋放鎖進入等待池。後面消費者線程3消費了一次,執行notifyAll喚醒了當前對象的所有等待池的線程。這個時候線程1搶到了鎖,進行一次生產,但是可能下次搶到鎖的是線程2,這時線程2上次wait之後的代碼將繼續執行下去,進行了一次生產,但是此時容器容量已經是11個了。如果我們用while的話,線程3這次會重新判定一次容量是否滿了,這樣滿了又會進入等待池,直到後面滿足條件才進行生產。
所以我們這裏必須用while,而不能用if。

方案二(推薦):使用Condition

使用Lock和Condition來實現, 對比兩種方式,Condition的方式可以更加精確的指定哪些線程被喚醒。

代碼:

public class PSproblem<T> {

    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10; //最多10個元素
    ReentrantLock lock = new ReentrantLock();
    Condition producer = lock.newCondition();//用於生產線程
    Condition consumer = lock.newCondition();//用於消費線程
    //消費過程
    public T get() {
        T t = null;
        try {
            lock.lock();
            while (lists.size() == 0) {
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //模擬消費
            t = lists.removeFirst();
            System.out.println("消費者" + Thread.currentThread().getName() + "消費產品");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            producer.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }
	//生產過程
    public void put(T t) {
        try {
            lock.lock();
            while (lists.size() == MAX) {
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //模擬生產
            lists.add(t);
            System.out.println("生產者" + Thread.currentThread().getName() + "生產了產品");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            consumer.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
       PSproblem<String> container = new PSproblem<>();
        //啓動2個生產者線程
        for (int i = 1; i <= 2; i++) {
            int index = i;
            new Thread(() -> {
                int count = 0;
                while (count++ < 5) {
                    container.put("包子");
                }
            }, Integer.toString(index)).start();
        }
        //啓動5個消費者線程
        for (int i = 1; i <= 5; i++) {
            int index = i;
            new Thread(() -> {
                int count = 0;
                while (count++ < 2) {
                    container.get();
                }
            }, Integer.toString(index)).start();
        }
    }
}

結果

在這裏插入圖片描述

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