Java中Executor服務概述
Executor 和 ExecutorService API 是管理和控制執行緒執行的重要工具。它們是 java.util.concurrent 套件的一部分。它們透過抽象線程創建、管理和同步的複雜性來簡化並發編程的過程。
Executors 是 java.util.concurrent 套件中的實用工具類,提供用於建立和管理不同類型的 ExecutorService 實例的工廠方法。它簡化了建立執行緒池的過程,讓我們可以輕鬆地建立和管理不同配置的執行器實例。
Executor API 它是從 Java 1.5 開始提供的介面。它提供了execute(Runnable command)方法。 這是基本接口,ExecutorService 擴展了該接口。給定的命令將在將來由新線程或線程池中的線程或同一線程執行,並且不會返回 void。
ExecutorService API 它是從 Java 1.5 開始提供的介面。它提供了多種方法來控制並發程式設計中任務的執行。它支援可運行和可調用任務。它傳回任務狀態的 Future。以下是最常用的方法。
submit() 接受 Callable 或 Runnable 任務並傳回 Future 型態結果。
invokeAny() 接受一組要執行的任務,並傳回任何一個任務成功執行的結果。
invokeAll() 接受要執行的任務集合,並以 Future 物件類型清單的形式傳回所有任務的結果。
shutdown() 不會立即停止執行器服務,但不接受新任務。一旦所有目前正在運行的任務完成,它就會關閉執行器服務。
shutdownNow() 會嘗試立即停止執行器服務,但不保證所有正在執行的任務會同時停止。
awaitTermination(long timeout, TimeUnit unit) 阻塞/等待,直到所有任務完成或發生超時或當前線程被中斷,以先發生者為準。當前線程將被阻塞。
ExecutorService 的類型
- FixThreadPool 它會建立具有指定執行緒數的固定大小執行緒池。提交的任務是並發執行的。如果沒有任務,則執行緒將處於空閒狀態,直到任務到達。如果線程繁忙,任務將被加入到佇列中。
ExecutorService fixedThreadPool = Executors.newScheduledThreadPool(5); Future<String> submit = fixedThreadPool.submit(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); return Thread.currentThread().getName(); }); fixedThreadPool.shutdown();
- CachedThreadPool 建立執行緒池並根據工作負載自動調整池中所需的執行緒數。如果執行緒空閒超過60秒,就會被終止。這對於動態負載非常有效。由於線程將在空閒超時後被殺死,因此這裡可以更好地利用資源。
ExecutorService fixedThreadPool = Executors.newCachedThreadPool(); Future<String> submit = fixedThreadPool.submit(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); return Thread.currentThread().getName(); }); fixedThreadPool.shutdown();
- SingleThreadExecutor 建立單線程,任務依序執行。這裡沒有並行處理。
ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor(); Future<String> submit = fixedThreadPool.submit(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); return Thread.currentThread().getName(); }); fixedThreadPool.shutdown()
- ScheduledThreadPool/ScheduledExecutor 它會建立一個線程或 trhead 池,能夠定期運行任務或在一定延遲後運行。
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // Single-threaded scheduler ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5); // Multi-threaded scheduler
scheduler.schedule(task, 10, TimeUnit.SECONDS); // Schedule task to run after 10 seconds. scheduler.scheduleAtFixedRate(task, 5, 10, TimeUnit.SECONDS); //It schedules a task to run every 10 seconds with an initial delay of 5 seconds. scheduler.scheduleWithFixedDelay(task, 5, 10, TimeUnit.SECONDS); //It schedules a task to run with a fixed delay of 10 seconds between the end of one execution and the start of the next, with an initial delay of 5 seconds. scheduler.schedule(() -> scheduler.shutdown(), 20, TimeUnit.SECONDS); //It schedules a shutdown of the scheduler after 20 seconds to stop the example.
向 ExecutorService 提交任務
可以使用execute() 和submit() 方法將任務提交給ExecutorService。 execute()方法用於Runnable任務,而submit()可以處理Runnable和Callable任務。 ”
executor.execute(new RunnableTask()); //fire-and-forgot executor.submit(new CallableTask()); //returns the status of task
關閉 ExecutorService
關閉 ExecutorService 以釋放資源非常重要。您可以使用 shutdown() 和 shutdownNow() 方法來執行此操作。
executor.shutdown(); // Initiates an orderly shutdown" executor.shutdownNow(); // Attempts to stop all actively executing tasks. executor.awaitTermination(long timeout, TimeUnit unit); //blocks the thread until all tasks are completed or timeout occurs or current thread is interrupted, whichever happens first. Returns `true `is tasks completed, otherwise `false`.
建議的關閉方法
executor.shutdown(); try { // Wait for tasks to complete or timeout if (!executor.awaitTermination(120, TimeUnit.SECONDS)) { // If the timeout occurs, force shutdown executor.shutdownNow(); } } catch (InterruptedException ex) { executor.shutdownNow(); Thread.currentThread().interrupt(); }
關於 Runnable
- Runnable 是一個接口,代表一個可以透過執行緒運行的任務。
- 我們可以使用Threads或Executor服務來執行Runnable任務。
- Runnable 有 run() 方法,且不傳回任何資料。
- 我們不能拋出已檢查的異常。
關於 Callable
- 1.5中引入
- 它有 call() 方法並傳回型別 V。
- 它包含 throws Exception 的意思,我們可以拋出檢查異常。
關於未來
- 它代表任何任務的未來結果。
- 請求處理完成後,結果最終會在Future中出現。
- boolean isDone() 傳回請求處理的狀態。如果完成則為 true,否則為 false。
- boolean cancel(boolean mayInterruptIfRunning) 取消提交的任務。如果我們將 mayInterruptIfRunning 傳遞為 false,那麼它不會取消已經啟動的任務。
- boolean isCancelled() 傳回任務是否取消。
- V get() 傳回任務結果。如果任務未完成,則阻塞執行緒。
- V get(long timeout, TimeUnit unit) 如有必要,最多等待給定時間以完成計算,然後檢索其結果。如果計算未完成,將在指定時間後拋出 TimeoutException。
快樂編碼和學習! ! !
如有任何問題請留言。
以上是Java中Executor服務概述的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

在使用IntelliJIDEAUltimate版本啟動Spring...

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...
