0

我想从可运行线程抛出异常,但不可能从线程抛出异常,所以我们可以将 chlild 线程的状态(任何异常)传递给父线程吗?

我阅读了有关 thread.join() 的信息,但在这种情况下,父线程等待子线程完成其执行。

在我的情况下,我的父线程在一段时间后一个接一个地启动线程,但是当任何线程抛出异常时,它应该将失败通知给客户,这样父线程就不会启动其他线程。

有什么方法可以实现吗?谁能帮我解决这个问题。

4

4 回答 4

4

要详细说明@zeller 的答案,您可以执行类似以下构造的操作:

//Use a Callable instead of Runnable to be able to throw your exception
Callable<Void> c = new Callable<Void> () {
    public Void call() throws YourException {
        //run your task here which can throw YourException
        return null;
    }
}

//Use an ExecutorService to manage your threads and monitor the futures
ExecutorService executor = Executors.newCachedThreadPool();
List<Future> futures = new ArrayList<Future> ();

//Submit your tasks (equivalent to new Thread(c).start();)
for (int i = 0; i < 5; i++) {
    futures.add(executor.submit(c));
}

//Monitor the future to check if your tasks threw exceptions
for (Future f : futures) {
    try {
        f.get();
    } catch (ExecutionException e) {
        //encountered an exception in your task => stop submitting tasks
    }
}
于 2012-08-30T09:32:36.177 回答
2

您可以使用Callable<Void>代替自定义线程池Runnable,也可以使用 anExecutorService代替自定义线程池。Callable-scall抛出异常。
使用 anExecutorService还可以管理跟踪submitFuture返回的 -s的正在运行的任务。通过这种方式,您将了解异常、任务完成等。

于 2012-08-30T09:20:29.807 回答
0

而不是实现Runnable接口实现Callable接口,返回值给父线程。

我想从可运行线程抛出异常,但不可能从线程抛出异常,所以我们可以将 chlild 线程的状态(任何异常)传递给父线程吗?

--> @assylias 说:不要通过返回值传递异常,只需抛出它。然后,您可以从父线程中捕获它,通常使用 future.get(); 调用将引发 ExecutionException。

而且,Callable.call() throws Exception这样你就可以直接扔了。

于 2012-08-30T09:17:41.133 回答
0

使用并发集合在父线程和子线程之间进行通信。在您的run方法中,执行一个try/catch块来接收所有异常,如果发生异常,请将其附加到用于与父级通信的集合中。父级应检查集合以查看是否发生任何错误。

于 2012-08-30T09:19:50.133 回答