BlockingQueue和SynchronousQueue
2022-12-16 本文已影响0人
arkliu
BlockingQueue四组api
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockQueueTest {
public static void main(String[] args) {
// test1();
// test2();
// test3();
test4();
}
// 抛出异常
public static void test1() {
ArrayBlockingQueue abq = new ArrayBlockingQueue<>(3);
abq.add("a");
abq.add("b");
abq.add("c");
// abq.add("d"); //超出队列容量,java.lang.IllegalStateException: Queue full
System.out.println("队首元素"+abq.element()); // element返回队首元素
System.out.println(abq.remove());
System.out.println(abq.remove());
System.out.println(abq.remove());
// System.out.println(abq.remove());//队列没有元素,抛出java.util.NoSuchElementException
}
// 有返回值,不抛出异常
public static void test2() {
ArrayBlockingQueue abq = new ArrayBlockingQueue<>(3);
abq.offer("a");
abq.offer("b");
System.out.println(abq.offer("c")); // true
System.out.println(abq.offer("d"));; //超出队列容量,不会抛出异常, 返回false
System.out.println("队首元素"+abq.peek()); // element返回队首元素
System.out.println(abq.poll());
System.out.println(abq.poll());
System.out.println(abq.poll());
System.out.println(abq.poll());// 队列没有元素,返回null
}
// 等待,一直阻塞
public static void test3() {
ArrayBlockingQueue abq = new ArrayBlockingQueue<>(3);
try {
abq.put("b");
abq.put("c");
abq.put("d");
// abq.put("a"); 超出容量后,一直阻塞等待
System.out.println(abq.take());
System.out.println(abq.take());
System.out.println(abq.take());
System.out.println(abq.take());// 队列没有元素,take一直阻塞等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 等待,超时阻塞
public static void test4() {
try {
ArrayBlockingQueue abq = new ArrayBlockingQueue<>(3);
abq.offer("a");
abq.offer("b");
System.out.println(abq.offer("c"));
System.out.println(abq.offer("d", 2, TimeUnit.SECONDS));
System.out.println(abq.poll());
System.out.println(abq.poll());
System.out.println(abq.poll());
System.out.println(abq.poll(2, TimeUnit.SECONDS));// 队列没有元素,超时返回null
} catch (InterruptedException e) {
e.printStackTrace();
};
}
}
SynchronousQueue
BlockingQueue<String>syQueue = new SynchronousQueue<>();
new Thread(()->{
try {
System.out.println("put first");
syQueue.put("first");
System.out.println("put second");
syQueue.put("second");
System.out.println("put thrid");
syQueue.put("thrid");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "syQueue put").start();
new Thread(()->{
try {
System.out.println("get:"+syQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println("get:"+syQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println("get:"+syQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "syQueue take").start();
2.gif