Executors 构建线程池

Executors包含一系列静态方法,可以用于构建线程池。

返回实现了 ExecutorService 接口的对象:

  • newCachedThreadPool
  • newFixedThreadPool(int threads)
  • newSingleThreadPool

返回实现了ScheduledExecutorService接口的对象

  • newScheduledThreadPool(int threads)
  • newScheduledSingleThreadPool

当用完一个线程池时,要调用shutdown或shutdownNow。

  • shutdown方法启动该线程池的关闭序列,执行器不再接受新任务。当所有任务完成后,线程池中的线程死亡。
  • showdownNow方法取消尚未开始的任务并试图中断正在运行的线程。

总结使用线程池需要做的事情:

  调用Executor的类方法newCachedThreadPool等;
  调用submit提交Runnable或Callable对象;
  如果想取消任务,或者提交的是Callable对象,要保存好Future对象;
  当不再提交任务时,调用shutdown方法。

 

posted @ 2015-06-06 20:50  一同  阅读(441)  评论(0编辑  收藏  举报