跟踪线程故障

我有一个HTML输出(显示线程的结果),并显示所有线程完成后(我等待使用连接完成)

有时单个线程可能有例外。

  • 如果我在任何线程中没有任何异常,我想在浏览器中显示HTML。
  • 如果我在所有线程中都有异常,那么我不想显示HTML
  • 如果我有一些异常,但不是所有的线程,那么我想要显示的HTML

什么是最简单的方法(最少量的代码)来实现一些可以跟踪线程是否失败的事情?

你可以使用CompletableFuture来达到这个目的,例如:

 val future1: CompletableFuture<String> = CompletableFuture.supplyAsync { println("This is your thread 1 code") "<html><head><title>" } val future2: CompletableFuture<String> = CompletableFuture.supplyAsync { println("This is your thread 2 code") if (Random().nextBoolean()) throw RuntimeException("Failed") "Title!</title></html></head>" } future1.thenCombine(future2, {result1, result2 -> result1 + result2}).whenComplete { s, throwable -> if (throwable != null) { println("failed") } else { println("done with $s") } } 

在Kotlin 1.1中,您将能够以更易读的方式编写这些代码:

 async { try { val s1 = await(future1) val s2 = await(future2) println(s1 + s2) } catch (e: Exception) { println("failed") } }