使用BlockingQueue实现生产者和消费者

这里我们让苹果作为被生产和消费的对象

apple.class

package com.blockQueue;


public class Apple {
private String name;
private String price;
//get和set方法省略
}

Producer.class

public class Producer<T>  implements Runnable{
    private  BlockingQueue<T>  queue;
    
public Producer(BlockingQueue<T> q) {
queue = q;
}

public void run() {
try {

while(true){
Apple apple = new Apple();
apple.setName("苹果");
apple.setName("10.8");
   queue.put((T) apple);
   System.out.println("生产者生产了一个苹果"+Thread.currentThread().getName());

  //这里我们是间隔一秒生产一个苹果
   Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}

consumer.class

public class Consumer<T> implements Runnable {


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


private BlockingQueue<T> queue;


public void run() {
while (true) {
try {
Apple apple= (Apple) queue.take();
System.out.println("消费者消费了一个苹果"+apple.getName());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

}


新建一个test.java

public static void main(String[] args) {
BlockingQueue<Apple> bApples = new  ArrayBlockingQueue<Apple>(10);  //容纳10个苹果的容器
Producer<Apple> producer = new Producer<Apple>(bApples);
Consumer<Apple> consumer1 = new Consumer<Apple>(bApples);
Consumer<Apple> consumer2 = new Consumer<Apple>(bApples);
ExecutorService service = Executors.newScheduledThreadPool(3);  //创建一个容量为3的线程池 
service.execute(producer);
service.execute(consumer1);
service.execute(consumer2);
service.shutdown();
}



你可能感兴趣的:(生产者和消费者)