Blokingqueue有四组api都可以对元素进行添加和移除,但还是有不一样的地方。
具体用法如下代码:
//1.会抛出异常
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.element());
}
//2.不会抛出异常,会有返回值,true和false
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.offer("d"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.offer("d"));
System.out.println(blockingQueue.peek());
}
//3.阻塞等待
void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
blockingQueue.put("d");//阻塞状态,等待释放
}
//4.超时等待
void test4() throws InterruptedException {
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.offer("d",2, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.offer("d"));
System.out.println(blockingQueue.peek());
}
//同步队列,put一个元素,take一个出来,保持同步。
void test5(){
SynchronousQueue synchronousQueue=new SynchronousQueue();
new Thread(()->{
try {
System.out.println("+a");
synchronousQueue.put("a");
System.out.println("+b");
synchronousQueue.put("b");
System.out.println("+c");
synchronousQueue.put("c");
System.out.println("+d");
synchronousQueue.put("d");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
synchronousQueue.take();
System.out.println("-a");
TimeUnit.SECONDS.sleep(3);
synchronousQueue.take();
System.out.println("-b");
TimeUnit.SECONDS.sleep(3);
synchronousQueue.take();
System.out.println("-c");
TimeUnit.SECONDS.sleep(3);
synchronousQueue.take();
System.out.println("-d");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2").start();
}