多線程 生產者與消費者2.0版(Condition版)

 原始版:多線程 生產者與消費者 遇到的問題以及解決方法

package demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.System.out;

 class ShareData {
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public void increment() throws Exception {
        //1判斷
        lock.lock();
        try {
            while (number >= 5) {
                //等待  不能生產
                condition.await();
            }
            //2  幹活
            number++;
            out.println(Thread.currentThread().getName() + "\t" + number);
            //通知喚醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

        public void decrement() throws Exception{
            //1判斷
            lock.lock();
            try {
                while (number == 0) {
                    //等待  不能消費
                    condition.await();
                }
                //2  幹活
                number--;
                out.println(Thread.currentThread().getName() + "\t" + number);
                //通知喚醒
                condition.signalAll();
            }catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lock.unlock();
            }

    }


}

public class ProdConsumer{
    public static void main(String[] args) {
         ShareData  shareData=new ShareData();

         new Thread(()->{
             for (int i=0;i<5;i++){
                 try {
                     shareData.increment();
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             }
         },"AA").start();

        new Thread(()->{
            for (int i=0;i<5;i++){
                try {
                    shareData.decrement();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(()->{
            for (int i=0;i<5;i++){
                try {
                    shareData.increment();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->{
            for (int i=0;i<5;i++){
                try {
                    shareData.decrement();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }

}

結果:


AA	1
AA	2
AA	3
AA	4
AA	5
BB	4
BB	3
BB	2
BB	1
BB	0
CC	1
CC	2
CC	3
CC	4
CC	5
DD	4
DD	3
DD	2
DD	1
DD	0

Process finished with exit code 0

 

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