Executor将线程的创建和线程的执行解耦,比较下面两个例子:

1:TaskExecutionWebServer.java

package chapter06;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; 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 serverSocket = new ServerSocket(100); while (true) {
final Socket connection=serverSocket.accept();
Runnable task=new Runnable() { //Runnable 不处理异常,callable 处理异常。
@Override
public void run() {
//handlerRequest (connection);
}
}; exec.execute(task); //将Runnable 交给executor
}
}
}

2:ThreadPerTaskWebServer ,不可取。

package chapter06;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; /**
* @program: GradleTestUseSubModule
* @author: Yafei Li
* @create: 2018-07-13 21:05
**/
public class ThreadPerTaskWebServer {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection=socket.accept();
Runnable task=new Runnable() {
@Override
public void run() {
// handleRequest(connection);
}
};
new Thread(task).start();
}
}
}

从上面两个例子可以看出  Executors 会创建线程池,从线程池中取出线程执行任务。可以控制线程的数量。

而Thread要为每个任务创建一个线程,浪费资源。  开销比较高。

所以Executors  能够将创建线程与任务执行解耦,  控制线程数量等优点。

当遇到new  Thread(Runnable).start();  时,应该换为Executor.execute(Runnable);

05-11 02:37