java - 嵌套线程可以为父线程抛出异常吗?

标签 java multithreading

我有一个 Controller 类和一个 Monitor 工作线程。 Controller 线程看起来像这样

public class ControllerA {
    public void ControllerA(){
        try{
            doWork();
        }
        catch(OhNoException e){
        //catch exception
        }

    public void doWork() throws OhNoException{

      new Thread(new Runnable(){
        public void run(){
        //Needs to monitor resources of ControllerA, 
        //if things go wrong, it needs to throw OhNoException for its parent
        }
        }).start();

      //do work here

    }
}

这样的设置可行吗?如何向线程外部抛出异常?

最佳答案

How do I throw exception to the outside of the thread?

有几种方法可以做到这一点。您可以在线程上设置 UncaughtExceptionHandler,或者您可以使用 ExecutorService.submit(Callable) 并使用从 Future.get() 中获取的异常

最简单的方法是使用ExecutorService:

ExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
Future<Void> future = threadPool.submit(new Callable<Void>() {
      public Void call() throws Exception {
         // can throw OhNoException here
         return null;
     }
});
// you need to shut down the pool after submitting the last task
threadPool.shutdown();
try {
   // this waits for your background task to finish, it throws if the task threw
   future.get();
} catch (ExecutionException e) {
    // this is the exception thrown by the call() which could be a OhNoException
    Throwable cause = e.getCause();
     if (cause instanceof OhNoException) {
        throw (OhNoException)cause;
     } else if (cause instanceof RuntimeException) {
        throw (RuntimeException)cause;
     }
}

如果你想使用 UncaughtExceptionHandler 那么你可以这样做:

 Thread thread = new Thread(...);
 final AtomicReference throwableReference = new AtomicReference<Throwable>();
 thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
     public void uncaughtException(Thread t, Throwable e) {
         throwableReference.set(e);
     }
 });
 thread.start();
 thread.join();
 Throwable throwable = throwableReference.get();
 if (throwable != null) {
     if (throwable instanceof OhNoException) {
        throw (OhNoException)throwable;
     } else if (throwable instanceof RuntimeException) {
        throw (RuntimeException)throwable;
     }
 }

关于java - 嵌套线程可以为父线程抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12897112/

相关文章:

java - 将代码从 Java 更改为 C

java - 调用 setPreferredWidth 时,JTable 列不会调整大小

java - 使用方法级注释测试 Spring 服务的好方法

java - 自建API跨域错误

java - LuceneAppEngine与Gradle的依赖

python - 无法与 python 并行(线程)telnet 连接

python - 定期检查事件/触发器的更优雅的方式?

php - 在 php 中运行异步函数

java - 检测谁创建了线程(使用 Eclipse)

java - Java线程中的 "blocked Count"和 "Waited Count"是什么意思?