由于您用completable-future 标记了您的问题,我想您正在考虑以下方向:
ExecutorService es = Executors.newSingleThreadExecutor();
CompletableFuture<Void> trigger = new CompletableFuture<>();
// submit your jobs
trigger.thenRunAsync(aRunnable, es);
trigger.thenRunAsync(anotherRunnable, es);
trigger.thenRunAsync(yetAnotherRunnable, es);
// and later-on
trigger.complete(null);
// now all Runnables will get submitted and executed
// you can use the same construct even after trigger point
// then, the runnable will get submitted immediately
trigger.thenRunAsync(aRunnable, es);
// finally
es.shutdown();
但请注意,这不会维持提交顺序,因为所有操作都被建模为仅取决于触发器。如果你需要保持订单,你可以使用类似的东西
CompletableFuture<Void> trigger = new CompletableFuture<>();
CompletableFuture<Void> order = trigger;
// submit your jobs
order = order.thenRunAsync(aRunnable, es);
order = order.thenRunAsync(anotherRunnable, es);
order = order.thenRunAsync(yetAnotherRunnable, es);
// and later-on
trigger.complete(null);
由于这只会在前一个作业完成后提交下一个作业,因此您必须小心关闭ExecutorService 的时间。但您可以使用order.join() 等待所有作业完成。
此外,当不同的线程可能以这种方式提交作业时必须小心,因为这样,order 变量的更新必须以线程安全的方式完成。