java實現生產者消費者模式(基於wait、notify)

示例代碼

package test;

import java.io.IOException;
import java.util.*;

/**
 * @Description TODO
 * @Author linmingxing
 * @Date 2020/3/5 下午11:52
 **/
public class Test {


    public static void main(String[] args) throws IOException, InterruptedException {

        List list = new ArrayList();
        Producer producer = new Producer(list);
        Consumer consumer = new Consumer(list);
        new Thread(producer).start();
        new Thread(consumer).start();
        new Thread(consumer).start();
        new Thread(consumer).start();
        new Thread(consumer).start();
        new Thread(consumer).start();
        new Thread(consumer).start();

    }
}


class Producer implements Runnable {

    List list;

    public Producer(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true){
            synchronized (list) {
                while (list.size() == 3) {
                    //等待消費者消費
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //即將生產出來的元素
                int prod = list.size() + 1;
                //生產元素
                list.add(prod);
                System.out.println("生產出===>" + prod);
                //因爲之前列表中的元素爲空,所以消費者線程正在等待,所以需要手動喚醒消費者線程
                list.notify();
            }
            try {
                //讓出當前線程的執行權,是線程處於就緒狀態
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {

    List list;

    public Consumer(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true){
            synchronized (list) {
                while (list.size() == 0) {
                    //暫時沒有元素可消費,使線程等待
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("消費掉===>" + list.remove(0));
                //喚醒正在等待的生產者線程
                list.notify();
            }
            try {
                //讓出當前線程的執行權,是線程處於就緒狀態
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

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