執行緒池執行器類



java.util.concurrent.ThreadPoolExecutor 是一個 ExecutorService,它使用可能存在的多個池化執行緒中的一個來執行每個提交的任務,通常使用 Executors 工廠方法進行配置。它還提供各種實用方法來檢查當前執行緒的統計資訊並控制它們。

ThreadPoolExecutor 方法

序號 方法及描述
1

protected void afterExecute(Runnable r, Throwable t)

在給定 Runnable 的執行完成時呼叫的方法。

2

void allowCoreThreadTimeOut(boolean value)

設定策略,該策略控制核心執行緒是否可能超時並終止(如果在保持活動時間內沒有到達任務),並在需要時到達新任務時替換。

3

boolean allowsCoreThreadTimeOut()

如果此池允許核心執行緒在保持活動時間內沒有到達任務時超時並終止,並在需要時到達新任務時替換,則返回 true。

4

boolean awaitTermination(long timeout, TimeUnit unit)

阻止,直到所有任務在關閉請求後完成執行,或者超時發生,或者當前執行緒被中斷,以先發生者為準。

5

protected void beforeExecute(Thread t, Runnable r)

在給定執行緒中執行給定 Runnable 之前呼叫的方法。

6

void execute(Runnable command)

在將來某個時間執行給定的任務。

7

protected void finalize()

當不再引用此執行器且它沒有執行緒時,呼叫 shutdown。

8

int getActiveCount()

返回正在積極執行任務的執行緒的大致數量。

9

long getCompletedTaskCount()

返回已完成執行的任務的大致總數。

10

int getCorePoolSize()

返回核心執行緒數。

11

long getKeepAliveTime(TimeUnit unit)

返回執行緒保持活動時間,這是超過核心池大小的執行緒在終止之前可能保持空閒的時間量。

12

int getLargestPoolSize()

返回曾經同時在池中的執行緒的最大數量。

13

int getMaximumPoolSize()

返回允許的最大執行緒數。

14

int getPoolSize()

返回池中當前的執行緒數。

15

BlockingQueuegetQueue()

返回此執行器使用的任務佇列。

15

RejectedExecutionHandler getRejectedExecutionHandler()

返回當前無法執行任務的處理程式。

16

long getTaskCount()

返回曾經安排執行的任務的大致總數。

17

ThreadFactory getThreadFactory()

返回用於建立新執行緒的執行緒工廠。

18

boolean isShutdown()

如果此執行器已關閉,則返回 true。

19

boolean isTerminated()

如果所有任務在關閉後都已完成,則返回 true。

20

boolean isTerminating()

如果此執行器在 shutdown() 或 shutdownNow() 後正在終止過程中但尚未完全終止,則返回 true。

21

int prestartAllCoreThreads()

啟動所有核心執行緒,使它們空閒等待工作。

22

boolean prestartCoreThread()

啟動一個核心執行緒,使它空閒等待工作。

23

void purge()

嘗試從工作佇列中刪除所有已取消的 Future 任務。

24

boolean remove(Runnable task)

如果存在,則從此執行器的內部佇列中刪除此任務,因此如果它尚未啟動,則不會執行它。

25

void setCorePoolSize(int corePoolSize)

設定核心執行緒數。

26

void setKeepAliveTime(long time, TimeUnit unit)

設定執行緒在終止之前可能保持空閒的時間限制。

27

void setMaximumPoolSize(int maximumPoolSize)

設定允許的最大執行緒數。

28

void setRejectedExecutionHandler(RejectedExecutionHandler handler)

設定無法執行任務的新處理程式。

29

void setThreadFactory(ThreadFactory threadFactory)

設定用於建立新執行緒的執行緒工廠。

30

void shutdown()

啟動有序關閉,其中先前提交的任務將被執行,但不會接受新任務。

31

List<Runnable> shutdownNow()

嘗試停止所有正在積極執行的任務,停止等待任務的處理,並返回正在等待執行的任務列表。

32

protected void terminated()

當執行器已終止時呼叫的方法。

33

String toString()

返回一個字串,標識此池及其狀態,包括執行狀態和估計的工作執行緒和任務計數的指示。

示例

下面的 TestThread 程式演示了在基於執行緒的環境中使用 ThreadPoolExecutor 介面。

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {
	
   public static void main(final String[] arguments) throws InterruptedException {
      ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();

      //Stats before tasks execution
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.submit(new Task());
      executor.submit(new Task());

      //Stats after tasks execution
      System.out.println("Core threads: " + executor.getCorePoolSize());
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.shutdown();
   }  

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task! Thread Name: " +
               Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed! Thread Name: " +
               Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

這將產生以下結果。

輸出

Largest executions: 0
Maximum allowed threads: 2147483647
Current threads in pool: 0
Currently executing threads: 0
Total number of threads(ever scheduled): 0
Core threads: 0
Largest executions: 2
Maximum allowed threads: 2147483647
Current threads in pool: 2
Currently executing threads: 2
Total number of threads(ever scheduled): 2
Running Task! Thread Name: pool-1-thread-2
Running Task! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-2
廣告