生产者消费者问题--BlockingQueue
# 代码:
public class App { public static void main(String[] args) { BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(6); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); producer.produce(5); consumer.consume(4); producer.produce(3); consumer.consume(2); } } class Producer { private BlockingQueue<Integer> queue; public Producer(BlockingQueue<Integer> queue) { this.queue = queue; } public void produce(final int val) { new Thread() { public void run() { try { int surplus = val; while (surplus > 0) { queue.put(1024); surplus--; System.out.printf("%s plan to produce (%d), actually produce (%d), queue size (%d) \n", Thread.currentThread().getName(), val, 1, queue.size()); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } } class Consumer { private BlockingQueue<Integer> queue; public Consumer(BlockingQueue<Integer> queue) { this.queue = queue; } public void consume(final int val) { new Thread() { public void run() { int surplus = val; try { while (surplus > 0) { queue.take(); surplus--; System.out.printf("%s plan to consume (%d), actually consume (%d), queue size (%d) \n", Thread.currentThread().getName(), val, 1, queue.size()); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }
# 输出:
Thread-0 plan to produce (5), actually produce (1), queue size (1)
Thread-3 plan to consume (2), actually consume (1), queue size (0)
Thread-2 plan to produce (3), actually produce (1), queue size (1)
Thread-1 plan to consume (4), actually consume (1), queue size (0)
Thread-2 plan to produce (3), actually produce (1), queue size (1)
Thread-3 plan to consume (2), actually consume (1), queue size (0)
Thread-0 plan to produce (5), actually produce (1), queue size (1)
Thread-2 plan to produce (3), actually produce (1), queue size (1)
Thread-1 plan to consume (4), actually consume (1), queue size (0)
Thread-0 plan to produce (5), actually produce (1), queue size (2)
Thread-1 plan to consume (4), actually consume (1), queue size (1)
Thread-1 plan to consume (4), actually consume (1), queue size (1)
Thread-0 plan to produce (5), actually produce (1), queue size (2)
Thread-0 plan to produce (5), actually produce (1), queue size (2)
# 有四个线程参与了这个过程,两个生产者,两个消费者