FIFO
BlockingQueue
- ArrayBlockingQueue
- LinkedBlockingQueue
- SynchronousQueue
什么时候使用阻塞队列
- 多线程并发处理,A调用B,如果B未执行完,A需要等待
- 多线程,线程池
使用队列
四组API
- 抛出异常
- 不会抛出异常
- 阻塞等待
- 超时等待
方式 | 抛出异常 | 不会抛出异常有返回值 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer | put | offer |
移除 | remove | poll | take | poll |
判断队列首部 | element | peek |
//List BlockingQueue Set
public class Test {
public static void main(String[] args) throws InterruptedException {
test4();
}
/*
* 抛出异常
*
* Exception in thread "main" java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(AbstractQueue.java:98)
at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
at com.ji.BlockingQueue.Test.test1(Test.java:20)
at com.ji.BlockingQueue.Test.main(Test.java:9)
* */
public static void test1(){
//队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.remove());
/*System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());*/
System.out.println(blockingQueue.element());
}
/*
* 不抛出异常有返回值 false
*
* */
public static void test2() {
//队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.peek());
}
/*
* 阻塞等待(一直阻塞)
*
* */
public static void test3() throws InterruptedException {
//队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("d"); //队列没有位置时会一直等待
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//System.out.println(blockingQueue.take()); // //队列没有元素时会一直等待
}
/*
* 阻塞等待(等待超时)
*
* */
public static void test4() throws InterruptedException {
//队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a", 2, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("b", 2, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("c", 2, TimeUnit.SECONDS));
//System.out.println(blockingQueue.offer("d", 2, TimeUnit.SECONDS));//等待超过两秒就退出
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}
}