如何在兩個SwingWorker 類別之間共享資料
簡介:
解決方案概述:
此解決方案利用 Executor 框架,特別是 Executors.newCachedThreadPool() 來同時執行多個 SwingWorker 任務。每個任務負責特定的操作,透過共享變數或方法呼叫進行資料交換。實作細節:
1.任務執行:
2.資料共享:
範例程式碼:
// SwingWorker task that performs a long-running operation and shares data class MyTask extends SwingWorker<Void, Integer> { private SharedData sharedData; // Shared variable for data exchange @Override protected Void doInBackground() { // Perform the long-running operation // Update the sharedData variable return null; } @Override protected void done() { // Notify other tasks that the data is ready for consumption } } // Main class that creates and executes the tasks class Main { private Executor executor = Executors.newCachedThreadPool(); private SharedData sharedData = new SharedData(); // Create shared data instance public static void main(String[] args) { // Create and execute multiple MyTask instances executor.execute(new MyTask(sharedData)); executor.execute(new MyTask(sharedData)); // Other thread operations and UI updates can continue here } }
注意:
此解決方案可確保完成任務之間的資料交換同步且線程安全,從而促進無縫通訊並防止資料損壞。 Executor 框架有效地管理任務執行,從而實現系統資源的最佳利用。以上是如何在兩個 SwingWorker 類別之間共用資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!