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

Bon*_*onk 7 java multithreading

我有一个Controller类和一个Monitor工作线程.控制器线程看起来像这样

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

    }
}
Run Code Online (Sandbox Code Playgroud)

这样的设置是否可行?如何将异常抛出到线程外部?

Gra*_*ray 7

如何将异常抛出到线程外部?

夫妻俩可以做到这一点.你可以UncaughtExceptionHandler在线程上设置一个,或者你可以使用an 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();
// this can throw ExecutionException
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;
     }
}
Run Code Online (Sandbox Code Playgroud)

如果你想使用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;
     }
 }
Run Code Online (Sandbox Code Playgroud)