使用BlockingQueue实现生产者,消费者模式

本文通过实例代码详细介绍了如何利用Java的BlockingQueue接口实现经典的生产者消费者问题。文章展示了生产者类、消费者类以及测试类的代码,并给出了运行后的输出结果,展示线程间的交互过程。

生产者类:

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
    BlockingQueue<String> queue;
    public Producer(BlockingQueue<String> queue){
        this.queue=queue;
    }

    @Override
    public void run() {
        try {
            String temp="消费线程"+Thread.currentThread().getName();
            System.out.println("生产线程"+Thread.currentThread().getName());
            queue.put(temp);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

消费者类:

import java.util.concurrent.BlockingQueue;

public class Customer implements Runnable {
    BlockingQueue<String> queue;
    public Customer(BlockingQueue<String> queue){
        this.queue=queue;
    }


    @Override
    public void run() {
        try {
            String temp=queue.take();
            System.out.println(temp);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试类:

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

public class Test {
    public static void main(String[] args) {
        BlockingQueue<String> queue=new LinkedBlockingQueue<String>(2);
        Producer producer=new Producer(queue);
        Customer customer=new Customer(queue);
        for(int i=0;i<5;i++){
            new Thread(producer,"Producer"+(i+1)).start();
            new Thread(customer,"Customer"+(i+1)).start();
        }
    }

}

输出结果:
生产线程Producer1
生产线程Producer2
消费线程Producer1
消费线程Producer2
生产线程Producer3
生产线程Producer4
消费线程Producer3
消费线程Producer4
生产线程Producer5
消费线程Producer5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值