Java 中幾種常用的線程池


Java 中幾種常用的線程池

 

轉載 : https://www.cnblogs.com/sachen/p/7401959.html

原創 2016年04月14日 23:29:01

概述:

在java內置API中操作線程所用到的類為Thread。創建線程一般有兩種方式,

  • 繼承Thread方式

  • 實現Runnable方式,並以runnable作為target創建Thread

在Android中的耗時任務一般都需要另開線程來執行,常常需要用線程池來管理這些線程,實現控制線程數,重用,控制執行和取消等功能。

Java線程池

Java提供了四種線程池

newCachedThreadPool :

可緩存線程池,若線程池長度超過處理需要,則回收空線程,否則創建新線程,線程規模可無限大。

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
  • 1

當執行第二個任務時第一個任務已經完成,會復用執行第一個任務的線程,而不用每次新建線程。

newFixedThreadPool :

定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
  • 1

定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()。

newScheduledThreadPool :

定長線程池,支持定時及周期性任務執行,類似Timer。

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
  • 1

使用實例:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); //表示延遲1秒后每3秒執行一次。 scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("delay 1 seconds, and excute every 3 seconds"); } }, 1, 3, TimeUnit.SECONDS);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

newSingleThreadExecutor :

單線程 的線程池,支持FIFO, LIFO, 優先級策略。

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
  • 1

通過觀察源碼,其中四種線程的創建都是創建一個ThreadPoolExecutor。其中ThreadPoolExecutor是ExecutorService接口的實現類。

java.util.concurrent

此包是java的並發編程包,其下定義了三個Executor接口

並發類圖

Executor:一個運行新任務的簡單接口。 
ExecutorService:擴展了Executor接口。添加了一些用來管理執行器生命周期和任務生命周期的方法。 
ScheduledExecutorService:擴展了ExecutorService。支持Future和定期執行任務。

實現類包括:ScheduledThreadPoolExecutor、ThreadPoolExecutor。 
java中提供的四種線程池,除了ScheduledThreadPool使用的是ScheduledThreadPoolExecutor,其他均為ThreadPoolExecutor。

ThreadPoolExecutor

ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

參數說明 
corePoolSize :線程池的核心線程數。 
maximumPoolSize :線程池所能容納的最大線程數。 
keepAliveTime :非核心線程閑置時的超時時長。超過該時長,非核心線程就會被回收。 
unit :keepAliveTime的時間單位。 
workQueue :線程池中的任務隊列。 
threadFactory:線程工廠,默認值DefaultThreadFactory。 
handler : 飽和策略,當線程池中的數量大於maximumPoolSize,對拒絕任務的處理策略,默認值ThreadPoolExecutor.AbortPolicy()。

參考: 
Java並發教程(Oracle官方資料)

Trinea:Java(Android)線程池

Java多線程:ThreadPoolExecutor詳解

並發編程網 - ifeve.com

線程池ThreadPoolExecutor介紹


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM