运行一个任务,可能在一个新的线程,也可能在一个线程池,也可能在调用线程来执行;具体需要看接口的实现类; void execute(Runnable command);
这个接口只提供运行线程任务的方法,并没有提供一个提交线程的任务的方法,提交线程任务的方法是在扩展类中实现的;所以此接口实现任务提交和任务执行进行解耦,用户无需关心如何创建线程,如何调度线程来执行任务;
用户只需要提供Runnable对象,将任务提交给执行器(Executor)中,有Executor框架完成线程的调配和任务的执行;
下面是一个顺序执行线程的任务的执行器;实现思路:
- 实现用一种委托的方式,也可以说是一种装饰设计模式,真正执行任务代码的构造方法中执行器(Executor);增加一个队列数据结构,来存储提交的线程任务,保证任务的顺序性;使用提交任务对象重新实现了一个Runnable接口,实现功能的增强,一个线程任务执行完毕之后,运行下一个任务执行任务的方法上要加上synchronized关键子保证线程安全,这是因为队列不是线程安全的,而且activate可能存在并发访问;
public class SerialExecutor implements Executor {
private Executor executor;
private Runnable activate;
private Queue tasks = new linkedList<>();
public SerialExecutor(Executor executor) {
this.executor = executor;
}
@Override
public synchronized void execute(Runnable command) {
tasks.offer(()->{
try {
command.run();
} finally {
scheduleNext();
}
});
// 如果之前还没有执行过任务,就开始执行;
if(this.activate == null) {
scheduleNext();
}
}
//返回队列头部的线程任务,并且赋值给runnable成员变量,
//如果此时队列为空,返回null,不尽兴任务调度;
private synchronized void scheduleNext(){
if((activate = tasks.poll()) != null) {
executor.execute(activate);
}
}



