java线程池

线程池的种类

java通过Executors 提供四种线程池,分别为:

  • newCachedThreadPool

    底层实现:
    new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
    
  • newFixedThreadPool

    底层实现:
    new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
    
  • newScheduledThreadPool

    底层实现:
    new ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());
    
  • newSingleThreadExecutor

    new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
    

拒绝策略

  • CallerRunsPolicy
当队列满时,启用调用主线程来完成任务
  • AbortPolicy
直接抛异常,任务中断
  • DiscardPolicy
直接丢弃
  • DiscardOldestPolicy
丢弃存在于队列最早的任务

阻塞队列类型

  • LinkedBlockingQueue
无限制队列,超出的任务会放到队列里等待执行
  • SynchronousQueue
同步队列,超出的任务会直接进行异常处理(比如直接丢弃)

results matching ""

    No results matching ""