日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

【Android】线程池

發布時間:2024/4/15 Android 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Android】线程池 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在Android中,主線程不能執行耗時的操作,否則可能會導致ANR。那么,耗時操作應該在其它線程中執行。線程的創建和銷毀都會有性能開銷,創建過多的線程也會由于互相搶占系統資源而導致阻塞的現象。這個時候,就需要使用線程池。

線程池的優點可以概括為以下幾點:

  • 1、重用線程池中的線程,避免線程創建、銷毀帶來的性能開銷;

  • 2、能有效地控制線程池的最大并發數,避免大量的線程之間因互相搶占系統資源導致的阻塞現象;

  • 3、能夠對線程進行簡單的管理。

以上線程池的優點引用自《Android開發藝術探索》

線程池的具體實現類為ThreadPoolExecutor,ThreadPoolExecutor繼承自AbstractExecutorService,AbstractExecutorService又實現了ExecutorService接口,ExecutorService繼承自Executor。

ThreadPoolExecutor有四個重載的構造方法:

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler); }public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,threadFactory, defaultHandler); }public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), handler); }public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler; }

最終都調用到了:

/*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @param corePoolSize the number of threads to keep in the pool, even* if they are idle, unless {@code allowCoreThreadTimeOut} is set* @param maximumPoolSize the maximum number of threads to allow in the* pool* @param keepAliveTime when the number of threads is greater than* the core, this is the maximum time that excess idle threads* will wait for new tasks before terminating.* @param unit the time unit for the {@code keepAliveTime} argument* @param workQueue the queue to use for holding tasks before they are* executed. This queue will hold only the {@code Runnable}* tasks submitted by the {@code execute} method.* @param threadFactory the factory to use when the executor* creates a new thread* @param handler the handler to use when execution is blocked* because the thread bounds and queue capacities are reached* @throws IllegalArgumentException if one of the following holds:<br>* {@code corePoolSize < 0}<br>* {@code keepAliveTime < 0}<br>* {@code maximumPoolSize <= 0}<br>* {@code maximumPoolSize < corePoolSize}* @throws NullPointerException if {@code workQueue}* or {@code threadFactory} or {@code handler} is null*/ public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler; }

對應這個方法中的參數:

  • corePoolSize:核心線程數。如果沒有設置allowCoreThreadTimeOut為true,則核心線程空閑時也不會銷毀。如果設置allowCoreThreadTimeOut為true,則受keepAliveTime控制,空閑時間超過keepAliveTime,會被回收。

  • maximumPoolSize:最大線程數。

  • keepAliveTime:非核心線程的空閑超時時長。超過這個時間,非核心線程會被回收。核心線程如果allowCoreThreadTimeOut為true,則在空閑超過這個時間也會被回收。

  • unit:超時的單位。

  • workQueue:線程池中的任務隊列。通過線程池的execute()方法提交的Runnable任務會被放入任務隊列中。

  • threadFactory:線程工廠。

  • handler:飽和策略。當任務隊列和線程池都滿后,對新提交的任務的處理策略。

ThreadPoolExecutor執行任務的規則:

  • 1、如果線程池中的線程數量未達到核心線程數量,則開啟一個新的核心線程來執行任務

  • 2、如果線程池中的線程數量已經大于等于核心線程數量,則會把新的任務放入任務隊列中

  • 3、如果任務隊列已滿,并且線程池中的線程未滿,則開啟非核心線程來處理新的任務

  • 4、如果任務隊列和線程池都已滿,則會交給handler飽和策略來處理

下面通過一個簡單的案例來驗證以上規則:

static class WorkThread implements Runnable {private String name;public WorkThread(String name) {this.name = name;}public void run() {try {Thread.sleep(5000);System.out.println("Thread: " + name + " work finish");} catch (Exception e) {e.printStackTrace();}} };Executor executor = new ThreadPoolExecutor(5, 100, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));for (int i = 0; i < 20; i++) {WorkThread thread = new WorkThread("" + i);executor.execute(thread);}

定義了一個線程池,核心線程池數量為5,線程數量為100,超時時間為60秒,任務隊列為5。在子線程中,sleep 5秒來模擬耗時的操作。然后開啟了20個線程,并放入線程池中執行。執行的結果如下:

Thread: 0 work finish Thread: 1 work finish Thread: 13 work finish Thread: 10 work finish Thread: 3 work finish Thread: 11 work finish Thread: 4 work finish Thread: 2 work finish Thread: 19 work finish Thread: 18 work finish Thread: 17 work finish Thread: 15 work finish Thread: 16 work finish Thread: 14 work finish Thread: 12 work finish Thread: 5 work finish Thread: 9 work finish Thread: 8 work finish Thread: 7 work finish Thread: 6 work finish

前五個線程在核心線程中執行,第6-10個線程由于核心線程已滿,因此在任務隊列中等待執行,第11-20個線程,由于核心線程和隊列都已滿,而線程池中還可以開啟線程,因此在非核心線程中執行。從結果來看,線程0-4,10-19會先執行完,然后任務隊列中的線程5-9才執行,驗證了以上的線程池任務執行規則。

為便于使用線程池,線程池還有幾種簡便的定義方法:

public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); }public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>()); }public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>())); }public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); }public ScheduledThreadPoolExecutor(int corePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue()); }

通過Executors的static方法來創建。其中:

  • FixedThreadPool:線程數量固定的線程池。從方法的定義來看,這種線程池里的線程全都是核心線程,并且沒有超時時間,任務隊列也是沒有限制的。

  • CachedThreadPool:這種線程池沒有核心線程,全是非核心線程,并且超時時間為60秒,任務隊列沒有限制。這種線程適合執行大量的耗時較短的任務。

  • SingleThreadExecutor:只有一個核心線程,沒有超時時間,任務隊列沒有限制。可以確保任務按順序執行。

  • ScheduledThreadPool:核心線程數量固定。非核心線程沒有限制。非核心線程閑置時會被立即回收。這類線程池適合執行定時任務和具有固定周期的重復任務。

轉載于:https://www.cnblogs.com/milovetingting/p/10735427.html

總結

以上是生活随笔為你收集整理的【Android】线程池的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。