阻塞队列-生产者与消费者模式

public class PC {


    public static void main(String[] args) {
        BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(5);

        for(int i = 0 ;i < 4 ; i ++){
            new Thread(new Productor(bq)).start();
            new Thread(new Consumer(bq)).start();
        }
    }



}
package com._ThreadPool._3;

import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Productor implements Runnable{
    private BlockingQueue<Integer> bq;

    public Productor(BlockingQueue<Integer> bq){
        this.bq = bq;
    }

    @Override
    public void run() {
        int i = 0 ;
        while(true){
            try {
                Thread.sleep(new Random().nextInt(5000));
                bq.put(i);
                System.out.println("队列中放入" + i + "队列中还有" + bq.size() + "个元素");
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package com._ThreadPool._3;

import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{
    private BlockingQueue<Integer> bq;

    public Consumer(BlockingQueue<Integer> bq){
        this.bq = bq;
    }
    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(new Random().nextInt(5000));
                Integer integer = bq.take();
                System.out.println("取出了" + integer +",队列里面还有" + bq.size() + "");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

posted @ 2018-10-22 16:20  式微胡不归  阅读(225)  评论(0编辑  收藏  举报