当我在看Executor的时候,当时不太理解execute方法的语义,导致了不太理解为什么说Executor接口执行已提交的 Runnable
任务的对象,此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节、调度等)分离开来的方法,下面我们来看一段代码:
public class TaskExecutionWebServer {
private static final int NTHREADS = 100;
private static final Executor exec
= Executors.newFixedThreadPool(NTHREADS);
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable task = new Runnable() {
public void run() {
handleRequest(connection);
}
};
exec.execute(task);
}
}
private static void handleRequest(Socket connection) {
// request-handling logic here
}
}
TaskExecutionWebServer中的Web服务器使用了一个带有有界线程池的Executor。通过executor方法将任务提交到工作队列中,工作线程反复地从工作队列中取出任务并执行它们(Executor的内部机制),这样就实现了请求处理任务的提交于任务的实际执行解耦开来。在上面的例子中,任务是在调用者的线程中执行的,调用者使用一定的机制来执行已经提交的任务
更常见的是,任务是在某个不是调用者线程的线程中执行的。以下执行程序将为每个任务生成一个新线程。
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}