面试的过程中,经常让写个消费者-生产者实例,这里有一个简单的实例:
阻塞队列的:
消费者:
public class Consumer implements Runnable {
/**
* 所有的数据会存在blockingDeque 里面,取blockingDeque就行
*/
private final BlockingQueue<Integer> blockingQeque;
public Consumer(BlockingQueue block) {
this.blockingQeque = block;
}
@Override
public void run() {
while (true) {
//模拟耗时
try {
Thread.sleep(1000);
decream(blockingQeque.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void decream(int a) {
System.out.println("thread name:" + Thread.currentThread().getName() + " 消耗:" + a);
}
}
生产者:
public class Product implements Runnable {
private final BlockingQueue<Integer> blockingQeque;
public Product(BlockingQueue block) {
this.blockingQeque = block;
}
@Override
public void run() {
while (true) {
try {
blockingQeque.put(incream());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int incream() {
int a = new Random().nextInt(10);
System.out.println("thread name:" + Thread.currentThread().getName() + " incream:" + a);
return a;
}
}
public static void main(String[] args) {
BlockingQueue<Integer> blockQueue=new ArrayBlockingQueue<Integer>(10);
Product product=new Product(blockQueue);
Consumer consumer1=new Consumer(blockQueue);
Consumer consumer2=new Consumer(blockQueue);
new Thread(product).start();
new Thread(consumer1).start();
new Thread(consumer2).start();
}
运行结果: