ThreadPoolExecutor运转机制详解
- - 移动开发 - ITeye博客看这个参数很容易让人以为是线程池里保持corePoolSize个线程,如果不够用,就加线程入池直至maximumPoolSize大小,如果还不够就往workQueue里加,如果workQueue也不够就用RejectedExecutionHandler来做拒绝处理. 但实际情况不是这样,具体流程如下:.
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
package com.laifeng.aio; import com.laifeng.bio.TimeServerHandler; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Created by wangqiao on 2015/4/15. */ public class TimeServer { public static void main(String[] args) throws IOException { int port = 8080; if(args != null && args.length > 0){ try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e){ } } ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("The time server is start in port:" + port); Socket socket = null; TimeServerHandlerExcutePool singleExcutor = new TimeServerHandlerExcutePool(50, 10000); while(true){ socket = server.accept(); singleExcutor.execute(new TimeServerHandler(socket)); } } finally { if (server != null) { System.out.println("The time server close"); server.close(); server = null; } } } }
package com.laifeng.aio; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by wangqiao on 2015/4/15. */ public class TimeServerHandlerExcutePool { private ExecutorService executor; public TimeServerHandlerExcutePool(int maxPoolSize, int queueSize) { executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize)); } public void execute(Runnable task) { executor.execute(task); } }