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

时间:2012-08-30 09:15:13

标签: java multithreading

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

我读到了关于thread.join()但是在这种情况下,父线程等待直到子线程完成其执行。

在我的情况下,我的父线程在一段时间后逐个启动线程,但是当任何线程抛出异常时,它应该通知paent有关失败,以便父线程不启动其他线程。

有没有办法实现它?任何人都可以帮我解决这个问题。

4 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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

  

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

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

另外,Callable.call() throws Exception所以你可以直接抛出它。

答案 3 :(得分:0)

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