首先来看下线程池的接口
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);
}
Executor是基于生产者-消费者模式,提交任务的操作相当于生成者,执行任务的相当于消费者。
我以书中的例子来说明线程池的创建
public class TaskExecutionWebServer {
private static final int NTHREADS = 10;
private static final Executor exec = Executors.newFixedThreadPool(NTHREADS);
/**
* @Title: main
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param args 设定文件
* @return void 返回类型
* @throws
* @author 闭门车
*/
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
}
}
Executor exec = Executors.newFixedThreadPool(NTHREADS);