An object that executes submitted Runnable tasks.
使用方式
- Executor executor = anExecutor();
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask1()); - Execuor 在简单的任务可以立即执行提交的任务
// 直接调用 Runnable的run方法, 在调度线程线程执行; 不会启动一个线程
class DirectExecutor implements Executor{
public void execute(Runnable r){
r.run();
}
}
3.大多数情况下 ,每个任务创建一个线程执行, 不是在调度者线程中执行
class ThreadPerTaskExecutor implements Executor{
public void execute(Runnable r){
new Thread(r).start();
}
}
4.执行串行任务的实现方式
class SerialExecutor implements Executor{
final Queue<Runnable> tasks = new ArrayDeque<>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor){
this.executor = executor;
}
public synchronized void execute(final Runnable r){
tasks.add(new Runnable(){
public void run(){
try{
r.run();
}finally{
scheduleNext();
}
}
});
if(active == null){
scheduleNext();
}
}
protected synchronized void scheduleNext(){
if( active = (tasks.poll()) != null ){
executor.execute(active);
}
}
}
-
ThreadPoolExecutor class provides an extensible thread pool implementation。
The Executors class provides convenient factory methods for these Executors。
Executor源码
public interface Executor{
/**
*The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation
*/
void execute(Runnable command)
}