代码片段-消费生产者模式

 

生产者生产数据到缓冲区中,消费者从缓冲区中取数据。

如果缓冲区已经满了,则生产者线程阻塞;

如果缓冲区为空,那么消费者线程阻塞。

BlockingQuene实现

package me.duzhi.demo.model;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class BlockingQueueConsumerProducer {
    public static void main(String[] args) {
        Resource resource = new Resource();
        Thread thread = new ProducerThread3(resource);
        Thread thread1 = new ConsumerThread3(resource);
        Thread thread2 = new ConsumerThread3(resource);
        thread.start();
        thread1.start();
        thread2.start();
    }
    //消费者线程
    static class ConsumerThread3 extends Thread {
        Resource resource;
        public ConsumerThread3(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep((long) (1000 * Math.random()));
                    resource.remove();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //生产者线程
    static class ProducerThread3 extends Thread {
        Resource resource;

        public ProducerThread3(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep((long) (1000 * Math.random()));
                    resource.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    static class Resource {
        BlockingQueue<Integer> integers = new LinkedBlockingDeque<Integer>();

        public void add() throws InterruptedException {
            integers.put(1);
            System.out.println("生产者" + Thread.currentThread().getName()
                    + "生产一件资源," + "当前资源池有" + integers.size() +
                    "个资源");

        }

        public void remove() throws InterruptedException {
            int i = integers.take();
            System.out.println("消费者" + Thread.currentThread().getName()
                    + "处理了一件资源," + "当前资源池有" + integers.size() +
                    "个资源");

        }
    }

}

除特别注明外,本站所有文章均为duzhi原创,转载请注明出处来自https://www.duzhi.me/article/12919.html

联系我们

******

在线咨询:点击这里给我发消息

邮件:ashang.peng#aliyun.com

QR code