1. 程式人生 > >java併發面試題(二)實戰

java併發面試題(二)實戰

如何使用阻塞佇列實現一個生產者和消費者模型?請寫程式碼

使用基於陣列的阻塞佇列,有限次取水果和放水果

package com.tom.jdk5.concurrent.collections;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/*************************************
* 使用阻塞佇列實現生產者消費者問題
*
* BlockingQueue的offer/poll操作不能滿足阻塞等待的效果
*
*
*************************************/

class Plate {
// 一個盤子,可以放10個水果
private BlockingQueue fruits = new LinkedBlockingQueue(10);

// 如果有水果,則取得,否則取不走
public String get() {
try {
return fruits.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}

public void put(String fruit) {
try {
fruits.put(fruit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

class Producer implements Runnable {

private Plate plate;

public Producer(Plate p) {
this.plate = p;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
this.plate.put("" + i);
System.out.println("第" + i + "個水果放入盤子");
Thread.sleep((long) (200 * Math.random()));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

class Consumer implements Runnable {

private Plate plate;

public Consumer(Plate p) {
this.plate = p;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
String j = this.plate.get();
System.out.println("第" + j + "個水果取出盤子");
Thread.sleep((long) (400 * Math.random()));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class ProducerConsumerTest {
public static void main(String[] args) {
Plate p = new Plate();
Producer producer = new Producer(p);
Consumer consumer = new Consumer(p);
new Thread(producer).start();
new Thread(consumer).start();

}
}