java线程自带队列的使用以及线程阻塞

java线程,设置队列的大小实现队列阻塞

public class QueueThreads {

    private static int nThreads = 4;//Runtime.getRuntime().availableProcessors() * 2 + 1;

    private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(4);//队列值大小设置为4

    private static ExecutorService executors = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue, new ThreadFactory() {

        private final String threadNamePrefix = "si_query_task_";

        private final AtomicInteger count = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, threadNamePrefix + count.getAndIncrement());
            //t.setDaemon(true);
            return t;
        }
    });

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            try {
                executors.execute(new Thread(new ThreadPoolTest(), "TestThread".concat("" + i)));
                int threadSize = queue.size();
                System.out.println("线程队列大小为-->" + threadSize);
            } catch(RejectedExecutionException e){
                System.out.println("阻塞异常");
            }catch (Exception e) {
                System.out.println("异常");
            }
            
        }
            executors.shutdown();
    }

    public void run() {
        synchronized (this) {
            try {
                System.out.println("线程名称:" + Thread.currentThread().getName());
                Thread.sleep(3000); //休眠是为了让该线程不至于执行完毕后从线程池里释放
            } catch (InterruptedException e) {
                //e.printStackTrace();
                
            }
        }
    }

}

本测试程序的队列设置为4,线程池的大小为4,循环开启10个任务执行结果:

分析:有8个任务执行成功了,线程处理完成立马会处理新的任务,但是出现了两个阻塞异常,原因是这两个任务来不及创建就被阻塞了,阻塞的结果就是丢弃。

原文地址:https://www.cnblogs.com/zyf-yxm/p/10436142.html