最近我試圖實現一個電子郵件服務,同時向每個用戶發送電子郵件。我當前的實現電流看起來像這樣:ExecutorService executor = Executors.newSingleThreadExecutor();tasks.forEach(executor::execute); // Each task sends an email to an userexecutorService.shutdown(); // Reclaim all the resources經過一番研究,我找到了一種新方法,即使用 Java 8CompletableFuture.runAsync(...)方法。使用這種方法我做了:ExecutorService executor = Executors.newSingleThreadExecutor();tasks.forEach(task -> CompletableFuture.runAsync(task, executor));executor.shutdown(); // Reclaim all resources現在我有點困惑,就正確性、可擴展性而言,解決我的問題的最佳方法是什么,以及解決我的問題的最現代/當前的方法是什么。
CompletableFuture runAsync 與使用 Executor
慕婉清6462132
2021-08-04 17:48:07