03.Executors
Executors 详解
并发


Executor, ExecutorService 和Executors

正如上面所说,这三者均是
Executor 和ExecutorService 这两个接口主要的区别是:ExecutorService 接口继承了Executor 接口,是Executor 的子接口Executor 和ExecutorService 第二个区别是:Executor 接口定义了execute()
方法用来接收一个Runnable
接口的对象,而ExecutorService 接口中的submit()
方法可以接受Runnable
和Callable
接口的对象。Executor 和ExecutorService 接口第三个区别是Executor 中的execute()
方法不返回任何结果,而ExecutorService 中的submit()
方法可以通过一个Future 对象返回运算结果。Executor 和ExecutorService 接口第四个区别是除了允许客户端提交一个任务,ExecutorService 还提供用来控制线程池的方法。比如:调用shutDown()
方法终止线程池。Executors 类提供工厂方法用来创建不同类型的线程池。比如: newSingleThreadExecutor()
创建一个只有一个线程的线程池, newFixedThreadPool(int numOfThreads)
来创建固定线程数的线程池,newCachedThreadPool()
可以根据需要创建新的线程,但如果已有线程是空闲的会重用已有线程。
下表列出了
Executor | ExecutorService |
---|---|
提供 |
提供 |
不能取消任务 | 可以通过 |
没有提供和关闭线程池有关的方法 | 提供了关闭线程池的方法 |
Hello World
下面是使用
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
// => Hello pool-1-thread-1
try {
System.out.println("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.err.println("tasks interrupted");
}
finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
System.out.println("shutdown finished");
}