package BlockingQueues;
import java.util.concurrent.ArrayBlockingQueue;
/**
* 用阻塞队列实现生产者消费者模式
* @author Administrator
*
*/
public class Test {
private int queueSize = 10;
private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(queueSize);
public static void main(String[] args) {
Test test = new Test();
test.new Consumer().start();
test.new producer().start();
}
/**
* 消费者
* @author Administrator
*/
class Consumer extends Thread{
@Override
public void run() {
consume();
}
private void consume() {
while (true) {
try {
queue.take();//获取并移除此队列的头部,在元素变得可用之前一直等待
System.out.println("queue.take() size:"+queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 生产者
* @author Administrator
*/
class producer extends Thread{
@Override
public void run() {
produce();
}
private void produce() {
while(true){
try {
queue.put("abc");//将指定的元素插入此队列的尾部,如果该队列已满,则等待可用的空间
System.out.println("queue.put() size:"+queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}