LinkedBlockingQueue、ArrayBlockingQueue、DelayQueue、TransferQueue、SynchronousQueue

1.LinkedBlockingQueue

/**
 * 使用阻塞同步队列 LinkedBlockingQueue 完成生产者消费者模式
 * 使用场景较多。
 */
public class T05_LinkedBlockingQueue {
    public static void main(String[] args) {

        BlockingQueue<String> queue = new LinkedBlockingQueue<>();

        // 启动生产者线程生产
        new Thread(() -> {
            for (int j = 0; j < 100; j++) {
                try {
            //若果容器满了,它会在这里等待,容器有空余了在插入数据 queue.put(
"aaa" + j); // put 方法,给容器添加元素,如果容器已经满了,则会阻塞等待 } catch (InterruptedException e) { e.printStackTrace(); } } }, "p").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } // 启用消费者线程消费 for (int i = 0; i < 5; i++) { new Thread(() -> { while (true) { try { System.out.println(Thread.currentThread().getName() + ":" + queue.take()); // 从队列中拿数据,如果空了,则会阻塞等待 } catch (InterruptedException e) { e.printStackTrace(); } } }, "c" + i).start(); } } }

2.ArrayBlockingQueue

/**
 * 使用阻塞有界同步队列 ArrayBlockingQueue 完成生产者消费者模式
 */
public class T06_ArrayBlockingQueue {
    public static void main(String[] args) throws InterruptedException {

        BlockingQueue queue = new ArrayBlockingQueue<>(10);
        for (int i = 0; i < 10; i++) {
            queue.put("a" + i);
        }
      //put的话在容器满了的情况下进行等待
//queue.put("a11"); // 会阻塞 //queue.add("a11"); // 会抛出异常 //System.out.println(queue.offer("a11")); // 会返回false System.out.println(queue.offer("a11", 1, TimeUnit.SECONDS)); // 会等待1s,返回false, 如果1s内有空闲,则添加成功后返回true } }

猜你喜欢

转载自www.cnblogs.com/gxlaqj/p/11699740.html