我现在有三个功能QThread: Destroyed while thread is still running message
,updateFieldFromCollection1()
和insertFromColletion1ToCollection2()
。
这些调用彼此之间并不相互依赖,但是当我想将它们链接在 completableFuture 中时,它们必须以给定的顺序一个接一个地运行。
deleteFromCollection1()
这些调用不会返回任何内容,因此我正在使用 completableFuture 的 runAsync 和 thenRun 方法。并据此链接了他们。我正在迭代msgIds,这是一个字符串列表。
update-> insert -> delete
以上代码可以正常工作(更新->插入->删除已完成),但会引发异常,例如repeatKey和bulkwrite。我确定问题是因为前一个线程完成其任务之前另一个线程正在启动。我希望它们异步运行,但我想通过避免冲突来约束线程。
我不确定我需要在哪里调整代码。
答案 0 :(得分:0)
msgIds.stream().forEach(msgId -> {
updateFieldFromCollection1();
CompletableFuture.runAsync(() ->
{insertFromColletion1ToCollection2()}).thenRun(() ->
{deleteFromCollection1()}));
更新必须在completableFuture之外进行。然后它就像一个魅力:)