利用LinkedBlockingQueue实现生产者-消费者模式

由于LinkedBlockingQueue 实现是线程安全的,实现了先进先出等特性,是作为生产者消费者的首选,LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。下面是一个例子,一看就明白了。


package com.spell.designPattern.producer_consumer;

import java.util.UUID;
import java.util.concurrent.BlockingQueue;

/**
* 生产者类,任务是产生个uuid放在队列中
*
* @author Administrator
*
*/
public class Producer implements Runnable {
private BlockingQueue<String> queue;

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

@Override
public void run() {
String uuid = UUID.randomUUID().toString();
try {
queue.put(uuid);
System.out
.println(Thread.currentThread() + " produce uuid:" + uuid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}

}

}



package com.spell.designPattern.producer_consumer;

import java.util.concurrent.BlockingQueue;

/**
* 消费者队列,任务是取得队列中的uuid打印下
*
* @author Administrator
*
*/
public class Consumer implements Runnable {
private BlockingQueue<String> queue;

public Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}

@Override
public void run() {
try {
String uuid = queue.take();
System.out
.println(Thread.currentThread() + " consume uuid:" + uuid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}

}
}



package com.spell.designPattern.producer_consumer;

import java.util.concurrent.LinkedBlockingQueue;

/**
* 测试类
*
* @author Administrator
*
*/
public class Tester {

public static void main(String[] args) throws InterruptedException {
// 队列
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
// 生产者一号
Producer producer = new Producer(queue);
// 生产者二号
Producer producer2 = new Producer(queue);
// 消费者
Consumer consumer = new Consumer(queue);

for (int i = 0; i < 15; i++) {
new Thread(producer).start();
}

for (int i = 0; i < 15; i++) {
new Thread(producer2).start();
}

for (int i = 0; i < 30; i++) {
new Thread(consumer).start();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值