执行后,将子线程的状态传递给其父线程



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

我读过thread.join(),但在这种情况下,父线程等待子线程完成它的执行。

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

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

要详细说明@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
    }
}

您可以使用可调用的<Void>而不是Runnable,也可以使用ExecutorService而不是自定义线程池。可调用的s call引发异常。
使用ExecutorService还可以管理正在运行的任务,跟踪提交返回的Future。通过这种方式,您将意识到异常、任务完成等。

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

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

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

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

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

最新更新