生产者消费者模式

package com.umbrella.container.producerConsumer;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

public class ProcuderConsumer<T> {

    private final LinkedList<T> list = new LinkedList<>();
    private final long MAX = 10;
    private int count = 0;

    public synchronized void put(T t) {
        while (list.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(t);
        ++count;
        //不能使用notify,否则可能叫醒的是一个消费者,若此时容器中没有元素,那么消费者就会一直等一直等。
        this.notifyAll();
    }

    public synchronized T get() {
        T t = null;
        while (list.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = list.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        ProcuderConsumer<String> pc = new ProcuderConsumer<>();
        //启动消费者进程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(pc.get());
                }
            }, "consumer " + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //启动生产者进程
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    pc.put(Thread.currentThread().getName() + " " + j);
                    System.out.println("produce " + j);
                }
            }, "producer " + i).start();
        }
    }
}

这个代码哪里写错了啊 我记得生产者消费者模式是一直运行下去 不会停的 但我写的这个很快就结束了

fenkapian
浏览 1216回答 0
0回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java