线程池中Executor、ExecuteService、Executors 的区别

来源:互联网 发布:mac air 电池循环次数 编辑:程序博客网 时间:2024/06/05 15:10
Executor、ExecuteService都是接口,ExecuteService继承于Executor,

Executor:接口
接口Executor里面只有一个execute方法: 
void execute(Runnable command)  

ExecutorService:接口
接口ExecutorService继承于Executor
public interface ExecutorService extends Executor {      void shutdown();      List<Runnable> shutdownNow();      boolean isShutdown();      boolean isTerminated();      boolean awaitTermination(long timeout, TimeUnit unit)      <T> Future<T> submit(Callable<T> task);      <T> Future<T> submit(Runnable task, T result);      Future<?> submit(Runnable task);      <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)      <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)      <T> T invokeAny(Collection<? extends Callable<T>> tasks)      <T> T invokeAny(Collection<? extends Callable<T>> tasks,                      long timeout, TimeUnit unit)  }  

Executors :类
直接援引JDK文档的说明来说一下这个类的作用
Factory and utility methods for Executor,ExecutorService, ScheduledExecutorService,ThreadFactory, and Callableclasses defined in this package. 
实例:
public class CacheThreadPool {      public static void main(String[] args) {          ExecutorService exec=Executors.newCachedThreadPool();          for(int i=0;i<5;i++)              exec.execute(new LiftOff());          exec.shutdown();//并不是终止线程的运行,而是禁止在这个Executor中添加新的任务      }  } 
上面例子用到了Executors类的newCachedThreadPool()方法。看一下这个方法:
public static ExecutorService newCachedThreadPool() {          return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                        60L, TimeUnit.SECONDS,                                        new SynchronousQueue<Runnable>());      }  
 在源码中我们可以知道两点
1、newCachedThreadPool()方法返回类型是ExecutorService;ExecutorService中有一个execute方法,这个方法的参数是Runnable类型。也就是说,将一个实现了Runnable类型的类的实例作为参数传入execute方法并执行,那么线程就相应的执行了。 
2、方法newCachedThreadPool()返回值实际是另一个类ThreadPoolExecutor的实例。

引用文档:
http://www.cnblogs.com/yezhenhan/archive/2012/01/07/2315645.html
http://cuisuqiang.iteye.com/blog/2019372

0 0
原创粉丝点击