1. 程式人生 > >Executor框架與Thread

Executor框架與Thread

解耦 ride r.java author rri web pub execute executors

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);

Executor框架與Thread