BlockingQueue实现生产者和消费者

BlockingQueue


适用场景:

生产者线程在一端生产,消费者线程在另一端消费,可以安全的实现生产者消费者问题(多个生产者 多个消费者)

生产者:

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

    private BlockingQueue<String> blockingQueue;

    public  Producer(BlockingQueue<String> blockingQueue){
        this.blockingQueue=blockingQueue;
    }
    @Override
    public void run(){
        String temp="Product";
        System.out.println(Thread.currentThread().getName()+":product");
        try {
            blockingQueue.put(temp);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

消费者:

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

    private BlockingQueue<String> blockingQueue;

    public  Consumer(BlockingQueue<String> blockingQueue){
        this.blockingQueue=blockingQueue;
    }
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName()+":consumer");
        try {
            blockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试代码:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class RunTest {

    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue=new LinkedBlockingQueue<String>(1);

        Producer producer=new Producer(blockingQueue);
        Consumer consumer=new Consumer(blockingQueue);

        for(int i=1;i<=5;i++){
            new Thread(producer,"Producer"+i).start();
            new Thread(consumer,"consumer"+i).start();
        }
    }
}

测试结果:

Producer1:Product
consumer1:Consumer
Producer2:Product
consumer2:Consumer
Producer3:Product
consumer3:Consumer
Producer4:Product
consumer5:Consumer
Producer5:Product
consumer4:Consumer

Process finished with exit code 0
还可以用来解决输出ABABABABAB的问题哦。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值