首页 > 编程语言 > 详细

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

时间:2019-02-26 11:45:40      阅读:131      评论:0      收藏:0      [点我收藏+]

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个任务执行成功了,线程处理完成立马会处理新的任务,但是出现了两个阻塞异常,原因是这两个任务来不及创建就被阻塞了,阻塞的结果就是丢弃。

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!