package demo;
import java.util.*;
import java.util.concurrent.*;
/**
* 这个类是用来测试阻塞队列的
* 当试图向一个队列添加元素,但是队列已经满时,或是想把一个元素移出队列而队列为空时
* 阻塞队列就会导致线程阻塞。
*
* @author king_wang
*
*/
public class BlockQueueTest {
private static int queueSize=10;
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(queueSize);
Runnable r1 = new PullThread(queue);
Thread t1 = new Thread(r1);
Runnable r2 = new OfferThread(queue);
Thread t2 = new Thread(r2);
System.out.println("开始启动线程");
t1.start();
t2.start();
System.out.println("结束线程");
}
}
class PullThread<InterruptException> implements Runnable {
public BlockingQueue<String> queue;
public PullThread(BlockingQueue<String> queue) {
this.queue = queue;
}
public void run(){
while(true)
{
try {
queue.take();
//queue.take()移除并返回队列头部的元素 如果队列为空,则阻塞
System.out.println("已经移走一个元素,一共"+queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class OfferThread<InterruptException> implements Runnable {
public BlockingQueue<String> queue;
public OfferThread(BlockingQueue<String> queue) {
this.queue = queue;
}
public void run() {
while(true)
{
try{
//queue.put() 添加一个元素 如果队列满,则阻塞.
queue.put("c++");
System.out.println("已插入一个元素,一共有"+queue.size());
}catch(InterruptedException e ){
e.printStackTrace();
}
}
}
}
阻塞队列(ArrayBlockingQueue)
最新推荐文章于 2024-05-23 19:22:12 发布