ArrayBlockingQueue的生产者和消费者。
学习写的测试,可能有BUG。
有了ArrayBlockingQueye,写生产者和消费者方便多了。
之前的一篇关于生产者和消费者的,一堆代码http://hongmin118.iteye.com/blog/865222
Java代码 收藏代码
package com.mhm.test1;
import java.util.concurrent.ArrayBlockingQueue;
/**
* 用ArrayBlockingQueue实现生产者和消费者
* @author Mahone
*
*/
public class BoundedBuffer {
public static void main(String[] args) {
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
/*
* 一个消费者,一直在消费
*/
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Integer i = queue.take();
System.out.println(Thread.currentThread().getName() + ” 取出” + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
/*
* 10个生产者同时生产,每人生产一次
*/
for (int i = 0; i < 10; i++) {
final int temp = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
synchronized (BoundedBuffer.class) {
queue.put(temp);
System.out.println(Thread.currentThread().getName() + ” 放入[" + temp + "]“);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}