BlockingQueue的一個小例子
生產者:
package test.a;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
for(int i=0;i<10;i++){
consume(queue.take());
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
void consume(Object x) {
System.out.println(x);
}
}
消費者:
package test.a;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) {
queue = q;
}
public void run() {
try {
for(int i=0;i<10;i++){
queue.put(produce(i));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
Object produce(int i) throws InterruptedException {
return "queue"+i;
}
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import test.Consumer;
import test.Producer;
public class Setup {
public static void main(String[] args) {
BlockingQueue q = new ArrayBlockingQueue(10);
//Producer p = new Producer(q);
//Consumer c1 = new Consumer(q);
//Consumer c2 = new Consumer(q);
//new Thread(c2).start();
//new Thread(p).start();
//new Thread(c1).start();
ExecutorService service = Executors.newCachedThreadPool();Consumer consumer = new Consumer(q);
Producer producer = new Producer(q);
service.submit(producer);
service.submit(consumer);
service.shutdown();
}
}