java阻塞队列

package com.quxiao.controller;


import java.util.concurrent.*;

/**
 * @program: package1
 * @author: quxiao
 * @create: 2023-09-27 15:22
 **/
public class t3 {
    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
//        test4();
    }

    private static void test4() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        try {
            //队列满等待指定时间后继续执行
            queue.offer("1", 1, TimeUnit.SECONDS);
            queue.offer("1", 1, TimeUnit.SECONDS);
            queue.offer("1", 1, TimeUnit.SECONDS);
            //队列为空等待指定时间后继续执行
            queue.poll(1, TimeUnit.SECONDS);
            queue.poll(1, TimeUnit.SECONDS);
            queue.poll(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void test3() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        try {
            //队列满一直等待队列头取出
            queue.put("1");
            queue.put("1");
            queue.put("1");
            //队列为空一直等待加入
            queue.take();
            queue.take();
            queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void test2() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        //队列满返回false
        queue.offer("1");
        queue.offer("1");
        queue.offer("1");
        //队列为空返回false
        queue.poll();
        queue.poll();
        queue.poll();
    }

    private static void test1() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        //队列满报错
        queue.add("1");
        queue.add("1");
        queue.add("1");
        //队列为空报错
        queue.remove();
        queue.remove();
        queue.remove();
    }
}

很好理解,没有多说的,直接上代码

你可能感兴趣的:(多线程,java,python,开发语言)