我有一些依賴于接口的工作流程抽象WorkflowStep:public interface WorkflowStep { public void executeStep();}現(xiàn)在我有了三個不同的類來實現(xiàn)這個接口:GetCoordinatesForWaypoints, DisplayDetails, PlaySounds我的目標是將它們與 鏈接起來CompletableFuture,目前每個重寫executeStep()方法都在可運行的環(huán)境中運行,如下所示:public class GetCoordinatesForEndpoints implements WorkflowStep { @Override public void executeStep() { new Thread(new Runnable() { @Override public void run() { //download coordinates from open street map }).start(); }}其他類的方法看起來類似?,F(xiàn)在我有一個開始工作流程的中心類。目前它看起來像這樣:public class DetailsDispatchWorkflow implements DispatchWorkflow { private List<WorkflowStep> workflowSteps; public DetailsDispatchWorkflow() { workflowSteps = new LinkedList<>(); } @Override public void start() { workflowSteps.add(new GetCoordinatesForEndpoints()); workflowSteps.add(new DisplayDetails()); workflowSteps.add(new PlaySounds()); workflowSteps.forEach(WorkflowStep::executeStep); }}現(xiàn)在我想用CompletableFutures 替換它。我嘗試的第一件事是做這樣的事情:ExecutorService executorService = Executors.newFixedThreadPool(5);CompletableFuture<WorkflowStep> workflowStepCompletableFuture = CompletableFuture.supplyAsync(() -> new GetCoordinatesForEndpoints().executeStep(), executorService);這給了我一個錯誤(我認為是因為被調(diào)用的方法返回 void)。僅調(diào)用構(gòu)造函數(shù)即可。我的下一步是將這些調(diào)用鏈接起來thenAccept(因為被調(diào)用的操作不返回值),但是當我追加時,這也不起作用.thenAccept(() -> new DisplayDetails().executeStep(), executorService);我收到一個錯誤,編譯器無法推斷函數(shù)接口類型。我的問題是:如何實現(xiàn)以下調(diào)用鏈:CompletableFuture<WorkflowStep> workflowStepCompletableFuture = CompletableFuture .supplyAsync(() -> new GetCoordinatesForEndpoints().executeStep(), executorService) .thenAccept(() -> new DisplayDetails().executeStep(), executorService) .thenAcceptAsync(() -> new PlaySounds().executeStep(), executorService);當所有實例化對象都實現(xiàn)相同的接口時?
1 回答

翻閱古今
TA貢獻1780條經(jīng)驗 獲得超5個贊
你的WorkflowStep
界面基本上相當于Runnable
:沒有輸入,沒有輸出。在CompletableFuture
API 中,您應該使用相應的runAsync()
和thenRunAsync()
方法:
CompletableFuture<Void> workflowStepCompletableFuture = CompletableFuture .runAsync(() -> new GetCoordinatesForEndpoints().executeStep(), executorService) .thenRunAsync(() -> new DisplayDetails().executeStep(), executorService) .thenRunAsync(() -> new PlaySounds().executeStep(), executorService);
這將使它們?nèi)慨惒竭\行,但按順序運行(就像您正在嘗試做的那樣)。
當然,您還應該Thread
從實現(xiàn)中刪除創(chuàng)建以使其有用。
添加回答
舉報
0/150
提交
取消