zoukankan      html  css  js  c++  java
  • 创建安全的ThreadPoolExecutor线程池


            LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<String>(1024);
            ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat("job-pool-%d").build();
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors()*2,
                    Runtime.getRuntime().availableProcessors()*2,
                    0,
                    TimeUnit.SECONDS,
                    linkedBlockingQueue,
                    THREAD_FACTORY,
                    new ThreadPoolExecutor.AbortPolicy());
            CountDownLatch countDownLatch = new CountDownLatch(list.size());
            try{
                for (Object object : list) {

                    //类要实现Callable接口
                    Future<Integer> future = threadPoolExecutor.submit(类);
                    resultList.add(future);
                    countDownLatch.countDown();

                   //循环判断queue中的线程大于1000,则等待1秒,直到小于1000位置,防止进行线程被拒绝
                    while(linkedBlockingQueue.size()>1000) {
                        Thread.sleep(1000);
                        System.out.println("暂停1秒");
                    }
                }

                //等待全部完成,在继续操作
                countDownLatch.await();

                //关闭线程池(不在接收新的线程)
                threadPoolExecutor.shutdown();

             }catch (Exception ex){

                //出现异常后,关闭线程池
                threadPoolExecutor.shutdownNow();
                ex.printStackTrace();
             }
            }finally {

                //最终判断线程池是否为空,进行关闭
                if(threadPoolExecutor!=null) {
                    threadPoolExecutor.shutdownNow();
                }
            }

    收藏文章数量从多到少与“把书读薄”是一个道理
  • 相关阅读:
    同样的请求img代码,单个html文件和项目中的html文件请求结果不一样
    CSS中A标签断字不换行问题(基础知识)
    句柄无效。 (异常来自 HRESULT:0x80070006 (E_HANDLE))
    Ext.Net 控件FileUploadField上传文件
    500内部服务器错误。你查找的资源存在问题,因而无法显示
    WebService 错误:无法加载协定为xxx的终结点配置部分,因为找到了该协定的多个终结点配置
    SyntaxError: unterminated string literal
    servlet入门
    myeclipse视图布局恢复
    JavaWEB开发入门
  • 原文地址:https://www.cnblogs.com/use-D/p/8797432.html
Copyright © 2011-2022 走看看