Executor框架
服務器應用中,串行處理機制通常無法提供高吞吐率或快速響應性。通過為每個請求創建一個新的線程來提供服務,從而實現更高的響應性。
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() {public void run() {handleRequest(connection);}};new Thread(task).start();}}private static void handleRequest(Socket connection) {//do something} }對于每個連接,主循環都將創建一個新線程來處理請求,而不是在主循環中進行處理。
在生產環境中,“為每個任務分配一個線程”這種方法存在一些缺陷,尤其是當需要創建大量線程時:
Executor接口
public interface Executor{void executor(Runnable command); }線程池
Executors 靜態工廠方法創建
- newFixedThreadPool 創建一個固定長度的線程池
- newCachedThreadPool 創建一個可緩存的線程池 規模不存在限制
- newSingleThreadPool 創建單個工作者線程來執行任務 異常后會替代
- newScheduledThreadPool 創建一個固定長度的線程池 以延時或定時方式來執行
以上實際都是通過ThreadPoolExecutor來創建的
public class Executors {public static ExecutorService newFixedThreadPool(int var0) {return new ThreadPoolExecutor(var0, var0, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());}public static ExecutorService newFixedThreadPool(int var0, ThreadFactory var1) {return new ThreadPoolExecutor(var0, var0, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), var1);}public static ExecutorService newSingleThreadExecutor() {return new Executors.FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));}public static ExecutorService newSingleThreadExecutor(ThreadFactory var0) {return new Executors.FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), var0));}//... }ThreadPoolExecutor 核心線程池的內部實現
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)workQueue 可以是以下幾種:
直接提交的隊列:SynchronousQueue
有界的任務隊列:ArrayBlockingQueue
無界的任務隊列:LinkedBlockingQueue
優先任務隊列:PriorityBlockingQueue
擴展線程池(extends java.util.concurrent.ThreadPoolExecutor)
ThreadFactory 線程工廠
每當線程池需要創建一個線程時,都是通過線程工廠方法來完成的。
public interface ThreadFactory{Thread newThread(Runnable r); }Executors中提供一個默認線程工廠的實現DefaultThreadFactory
static class DefaultThreadFactory implements ThreadFactory {private static final AtomicInteger poolNumber = new AtomicInteger(1);private final ThreadGroup group;private final AtomicInteger threadNumber = new AtomicInteger(1);private final String namePrefix;DefaultThreadFactory() {SecurityManager s = System.getSecurityManager();group = (s != null) ? s.getThreadGroup() :Thread.currentThread().getThreadGroup();namePrefix = "pool-" +poolNumber.getAndIncrement() +"-thread-";}public Thread newThread(Runnable r) {Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(),0);if (t.isDaemon())t.setDaemon(false);if (t.getPriority() != Thread.NORM_PRIORITY)t.setPriority(Thread.NORM_PRIORITY);return t;}}Executor的生命周期
為了解決執行服務的生命周期問題,Executor擴展了ExecutorService接口,添加了一些用戶生命周期管理的方法(還有一些用于任務提交的便利方法)。
public interface ExecutorService extends Executor{void shutdown();List<Runnable> shutdownNow();boolean isShutdown();boolean isTerminated();<T> Future<T> submit(Callable<T> task);// ..... }ExecutorService的生命周期有三種狀態:運行,關閉和已終止
平緩的關閉方式–shutdown:不再接受新的任務,同時等待已經提交的任務執行完成( 包括那些還未開始執行的任務 )。
粗暴的關閉方式–shutdownNow:它將嘗試取消所有運行中的任務,并且不再啟動隊列中尚未開始執行的任務。
JVM只有在所有非守護線程全部終止后才會退出,如果無法正確地關閉Executor,那么JVM將無法結束。
轉載于:https://www.cnblogs.com/lucare/p/9312662.html
總結
以上是生活随笔為你收集整理的Executor框架的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sharepoint column中的图
- 下一篇: 动态排序JavaBean