class MyClass {
/**
*
* 定义装苹果的篮子
*
*/
public class Basket {
BlockingQueue<String> basket =
new LinkedBlockingQueue<String>(
3);
public void produce()
throws InterruptedException {
basket.put(
"An apple");
}
public String
consume()
throws InterruptedException {
return basket.take();
}
}
class Producer implements Runnable {
private String instance;
private Basket basket;
public Producer(String instance, Basket basket) {
this.instance = instance;
this.basket = basket;
}
public void run() {
try {
while (
true) {
System.out.println(
"生产者准备生产苹果:" + instance);
basket.produce();
System.out.println(
"!生产者生产苹果完毕:" + instance);
Thread.sleep(
300);
}
}
catch (InterruptedException ex) {
System.out.println(
"Producer Interrupted");
}
}
}
class Consumer implements Runnable {
private String instance;
private Basket basket;
public Consumer(String instance, Basket basket) {
this.instance = instance;
this.basket = basket;
}
public void run() {
try {
while (
true) {
System.out.println(
"消费者准备消费苹果:" + instance);
System.out.println(basket.consume());
System.out.println(
"!消费者消费苹果完毕:" + instance);
Thread.sleep(
1000);
}
}
catch (InterruptedException ex) {
System.out.println(
"Consumer Interrupted");
}
}
}
public static void main(String[] args) {
MyClass test =
new MyClass();
Basket basket = test.
new Basket();
ExecutorService service = Executors.newCachedThreadPool();
Producer producer = test.
new Producer(
"生产者001", basket);
Producer producer2 = test.
new Producer(
"生产者002", basket);
Consumer consumer = test.
new Consumer(
"消费者001", basket);
service.submit(producer);
service.submit(producer2);
service.submit(consumer);
}
}
当注释掉
Consumer consumer = test.new Consumer("消费者001", basket)
service.submit(consumer)
及没有消费者,打印如下:
生产者准备生产苹果:生产者001
!生产者生产苹果完毕:生产者001
生产者准备生产苹果:生产者002
!生产者生产苹果完毕:生产者002
生产者准备生产苹果:生产者001
生产者准备生产苹果:生产者002
!生产者生产苹果完毕:生产者001
生产者准备生产苹果:生产者001
验证了上面对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素
同样,注释掉
Producer producer = test.new Producer("生产者001", basket)
Producer producer2 = test.new Producer("生产者002", basket)
service.submit(producer)
service.submit(producer2)
及没有生产者,打印如下:
消费者准备消费苹果:消费者001
验证了上面对于take方法,若队列为空,发生阻塞,等待有元素。
阻塞队列LinkedBlockingQueue用法
标签: