美文网首页
BlockingQueue 实现生产者消费者模式

BlockingQueue 实现生产者消费者模式

作者: 小明17 | 来源:发表于2019-06-03 21:19 被阅读0次

1.Producer

import java.util.concurrent.BlockingQueue;

public class Producer extends Thread {
    private BlockingQueue<Integer> sharedQueue;

    public Producer(BlockingQueue<Integer> shareQueue){
        super("PRODUCER");
        this.sharedQueue = shareQueue;
    }

    public void run(){
        //no synchronization needed
        for(int i=0; i<10; i++){
            try{
                System.out.println(getName() + " produced " + i);
                sharedQueue.put(i);
                Thread.sleep(2000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

2.Consumer

import java.util.concurrent.BlockingQueue;

public class Consumer extends Thread {
    private BlockingQueue<Integer> shareQueue;

    public Consumer(BlockingQueue<Integer> shareQueue) {
        super("CONSUMER");
        this.shareQueue = shareQueue;
    }

    public void run(){
        try{
            while(true){
                Integer item = shareQueue.take();
                System.out.println(getName() + " consumed " + item);
            }
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

3.main

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

public class Solution {

    public static void main(String[] args) {
        BlockingQueue<Integer> shareQueue = new LinkedBlockingDeque<>();

        Producer P = new Producer(shareQueue);
        Consumer C = new Consumer(shareQueue);

        P.start();
        C.start();
    }
}

相关文章

网友评论

      本文标题:BlockingQueue 实现生产者消费者模式

      本文链接:https://www.haomeiwen.com/subject/upihxctx.html