Contents
  1. 1. java concurrency Executor概述

java concurrency Executor概述

从java 5开始,java并发api就提供了Executor框架,把任务的创建和任务的执行分开。使用executor,我们仅仅需要实现Runnable接口并把它提交给executor处理即可。executor框架负责任务的执行。并且不仅仅如此,通过使用线程池来提高运行效率。当我们把一个任务交给executor处理时,executor首先会在thread pool中寻找可用的Thread,这样可以避免创建新的Thread对象,从而节约时间,加快任务的执行。

Executor框架的另外一个好处是其提供了Callable接口。Callable接口和Runnable借口类似,但是Callable提供以下2个改进:

  • Callable接口主要的方法是call(),并且此方法可以返回一个数据类型
  • 当把一个实现Callable接口的对象交给一个executor对象处理时,executor对象会返回一个实现Future接口的对象。通过对此对象的操作来控制Callable任务执行的状态和结果。

下图是java concurrency api中executor框架中类和接口的uml图:
executor uml图

下面是接口Executor的实现代码

1
2
3
public interface Executor{
void execute(Runnable command);
}

下一篇将一一介绍上图类和接口的使用。

Contents
  1. 1. java concurrency Executor概述