线程池Executor
目录
1、线程池简介
线程池是在java开发中很重要的一个概念,Android中的线程池和和java是保持一致的,并无什么区别。线程池是一个抽象的概念,在java中是一个接口类,用Executor表示, 具体实现类为ThreadPoolExecutor,它们位于java.util.concurrent包下面,这个接口类很短,而且接口声明就只有一个,并且注释中说明了一些情况怎么使用,
package java.util.concurrent;
public interface Executor {
/**
* Executes the given command at some time in the future. 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.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}
上面省略了注释,可以看注释,很管用,上面有模版,教我们怎么创建一个自己线程池,其中有段是这么说的:许多线程池的实现类对将要执行的任务的方式和时间做了限制,下面展示了串型线程池在执行任务的时候,从一个任务到下一个任务的过程。
下面代码来至注释中的举例,说明了一个从任务如何进入到下一个任务的串行执行过程:
package demo.xx.patten.xx;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
public class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<>();
final Executor executor;
Runnable active;
public SerialExecutor(Executor executor) {
this.exec