生产者消费者 BlockingQueue 实现
程序员文章站
2022-04-21 10:36:08
...
BlockingQueue是一个线程安全的队列,本身的部分方法实现了线程之间的调度,实现生产者消费者非常方便,比synchronized,wait更容易控制,不过看BlockingQueue的实现类ArrayBlockingQueue的源码,主要还是使用Lock和条件变量Condition来实现,足以见的Lock的灵活和强大,下面是我写的实现:
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Created by Administrator on 14-4-8. */ public class BlockingQueueDemo { public static void main (String[] args) { BlockingQueue blockingQueue = new ArrayBlockingQueue(GodOwn.MAX_SIZE); GodOwn godOwn = new GodOwn(blockingQueue); for (int i = 0; i < 10; i++) { new Producer(godOwn).start(); } for (int i = 0; i < 10; i++) { new Reducer(godOwn).start(); } } } class GodOwn { /** * 仓库能盛放馒头最大数量 */ public static final int MAX_SIZE = 3; private BlockingQueue<Mantou> blockingQueue; GodOwn (BlockingQueue<Mantou> blockingQueue) { this.blockingQueue = blockingQueue; } public void produce () throws InterruptedException { Mantou mantou = new Mantou(); blockingQueue.put(mantou); System.out.println("生产了一个,仓库还有" + blockingQueue.size()); } public void reduce () throws InterruptedException { blockingQueue.take(); System.out.println("消费了一个,仓库还有" + blockingQueue.size()); } } /** * 消费者 */ class Producer extends Thread { private GodOwn godOwn; Producer (GodOwn godOwn) { this.godOwn = godOwn; } public void run () { try { godOwn.produce(); } catch (Exception e) { e.printStackTrace(); } } } /** * 消费者 */ class Reducer extends Thread { private GodOwn godOwn; Reducer (GodOwn godOwn) { this.godOwn = godOwn; } public void run () { try { godOwn.reduce(); } catch (Exception e) { e.printStackTrace(); } } } /** * 馒头 */ class Mantou { }