线程池

java创建线程池有两种方法

Executors,ThreadPoolExecutor

不建议Executors去创建,而是通过ThreadPoolExecutor。

Executors各个方法的弊端:
   1)newFixedThreadPool和newSingleThreadExecutor:
     主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。
   2)newCachedThreadPool和newScheduledThreadPool:
     主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。

 

定时调度器//org.apache.commons.lang3.concurrent.BasicThreadFactory
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());   
  
  // com.google.common.util.concurrent.ThreadFactoryBuilder;
  ThreadFactory build = new ThreadFactoryBuilder().build();
  ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(8, build);
线程池: ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build(); //Common Thread Pool ExecutorService pool = new ThreadPoolExecutor(5, 200,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); pool.execute(()-> System.out.println(Thread.currentThread().getName())); pool.shutdown();

 

posted @ 2018-08-09 11:03  jwcc  阅读(144)  评论(0编辑  收藏  举报