国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

多線程 線程池ThreadPoolExecutor介紹

2019-11-08 00:29:47
字體:
來源:轉載
供稿:網(wǎng)友

1. 使用線程池好處

每次都new Thread的弊端如下:

每次new Thread新建對象性能差。線程缺乏統(tǒng)一管理,可能無限制新建線程,相互之間競爭,及可能占用過多系統(tǒng)資源導致死機或oom。缺乏更多功能,如定時執(zhí)行、定期執(zhí)行、線程中斷。

線程池的好處在于:

重用存在的線程,減少對象創(chuàng)建、消亡的開銷,性能佳。可有效控制最大并發(fā)線程數(shù),提高系統(tǒng)資源的使用率,同時避免過多資源競爭,避免堵塞。提供定時執(zhí)行、定期執(zhí)行、單線程、并發(fā)數(shù)控制等功能。

2. 概述

java里面線程池的頂級接口是Executor,但是嚴格意義上講Executor并不是一個線程池,而只是一個執(zhí)行線程的工具。真正的線程池接口是ExecutorService和ScheduledExecutorService,實現(xiàn)為ThreadPoolExecutor和ScheduledThreadPoolExecutor。

3. ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {}corePoolSize 線程池的核心線程數(shù)。在沒有設置allowCoreThreadTimeOut為true的情況下,核心線程會在線程池中一直存活,即使處于閑置狀態(tài)。maximumPoolSize 線程池所能容納的最大線程數(shù)。當活動線程達到這個數(shù)值后,后續(xù)任務將會根據(jù)handler來處理。keepAliveTime 非核心線程閑置時的超時時長。超過該時長,非核心線程就會被回收。若allowCoreThreadTimeOut屬性為true時,該時長同樣會作用于核心線程。unit keepAliveTime的時間單位。workQueue 線程池中的任務隊列,通過線程池的execute()方法提交的Runnable對象會存儲在該隊列中。 可選子類: BlockingQueue可選子類threadFactory 線程工廠,為線程池提供創(chuàng)建新線程的功能。ThreadFactory是一個接口。Executors中提供了DefaultThreadFactory。RejectedExecutionHandler the handler to use when execution is blocked because the thread bounds and queue capacities are reached。當任務無法被執(zhí)行時(超過線程最大容量maximum并且queue已經(jīng)被排滿了)的處理策略。默認為AbortPolicy,直接拋出異常。 RejectedExecutionHandler

4. ThreadPoolExecutor執(zhí)行規(guī)則

先判斷線程數(shù)量是否達到核心線程數(shù)。如果沒有直接啟動一個核心線程來執(zhí)行任務。否則執(zhí)行2.判斷任務隊列是否已滿。如果沒滿則插入到任務隊列等待。否則執(zhí)行3.判斷線程數(shù)量是否達到最大線程數(shù)maxiumPoolSize。如果沒有則直接開啟非核心線程執(zhí)行任務。否則執(zhí)行4.拒絕執(zhí)行此任務,調(diào)用handler.rejectedExecution來進行處理。 線程池處理流程

5. 示例:

public static Executor createExecutor(int threadPoolSize, int threadPRiority) { BlockingQueue<Runnable> taskQueue = new LinkedBlockingDeque<Runnable>(); return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS, taskQueue, createThreadFactory(threadPriority, "pool-")); }private static ThreadFactory createThreadFactory(int threadPriority, String threadNamePrefix) { return new DefaultThreadFactory(threadPriority, threadNamePrefix); } //代碼來自UniversalImageLoader。支持設置線程優(yōu)先級。 private 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; private final int threadPriority; DefaultThreadFactory(int threadPriority, String threadNamePrefix) { this.threadPriority = threadPriority; group = Thread.currentThread().getThreadGroup(); namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-"; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);//重命名線程,方便排查問題。 if (t.isDaemon()) t.setDaemon(false); t.setPriority(threadPriority);//設置線程優(yōu)先級 return t; } }

6. Executors提供的線程池

FixedThreadPool 線程數(shù)量固定的線程池,無限的任務隊列,只有核心線程。最多只有nThreads個任務在并行處理,之后都在排隊等待。 public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }CachedThreadPool 適合執(zhí)行大量耗時較少的任務。沒有核心線程,即沒有任務時,它幾乎不占用任何系統(tǒng)資源。These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. SynchronousQueue不緩存任何一個任務,當即執(zhí)行。 public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }ScheduledThreadPool Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.ScheduledThreadPoolExecutor源碼解析 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 10L, MILLISECONDS, new DelayedWorkQueue()); }SingleThreadExecutor 確保所有的任務都在一個線程中按順序執(zhí)行,使得這些任務之間不需要處理線程同步問題。Creates an Executor that uses a single worker thread Operating off an unbounded queue. public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }

7. 實用中

Android中,可以根據(jù)需要自己創(chuàng)建線程池。frameWork提供的AsyncTask確實不好用。設置線程的優(yōu)先級 android.os.Process.setThreadPriority (int priority) priority:【-20, 19】,高優(yōu)先級 -> 低優(yōu)先級. THREAD_PRIORITY_DEFAULT,默認的線程優(yōu)先級,值為0 THREAD_PRIORITY_LOWEST,最低的線程級別,值為19 THREAD_PRIORITY_BACKGROUND 后臺線程建議設置這個優(yōu)先級,值為10 THREAD_PRIORITY_MORE_FAVORABLE 相對THREAD_PRIORITY_DEFAULT稍微優(yōu)先,值為-1 THREAD_PRIORITY_LESS_FAVORABLE 相對THREAD_PRIORITY_DEFAULT稍微落后一些,值為1 Runnable runnable = new Runnable() { @Override public void run() {//A linux priority level, from -20 for highest scheduling priority to 19 for lowest scheduling priority.-20最高,19最低 android.os.Process.setThreadPriority(Thread.MAX_PRIORITY); } };

也可以使用PriorityBlockingQueue來實現(xiàn)調(diào)度任務優(yōu)先級。

參考: 聊聊并發(fā),JAVA線程池的分析和使用 Java自帶線程池和隊列詳解 Trinea的介紹new Thread的弊端及Java四種線程池的使用 使用線程池處理異步任務


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 马山县| 疏附县| 花莲县| 贵德县| 武夷山市| 漳州市| 内黄县| 阿克陶县| 株洲县| 买车| 蒙自县| 台中县| 阿拉善右旗| 桐柏县| 义马市| 兴宁市| 忻城县| 尼勒克县| 兰州市| 左贡县| 永丰县| 汾西县| 怀来县| 陆河县| 奉贤区| 大厂| 舒兰市| 乐陵市| 抚顺市| 东阿县| 巢湖市| 安顺市| 内丘县| 霍林郭勒市| 新乐市| 聂荣县| 木里| 昌邑市| 康乐县| 仪陇县| 贵州省|