简体   繁体   English

从运行线程捕获异常

[英]Catch Exception from running Thread

I want to catch an exception from a running thread and handle it in the calling thread. 我想从正在运行的线程中捕获异常并在调用线程中处理它。 How would I to that the best way? 我将如何以最好的方式?

try {
  Runnable connect = new Runnable() {
    public synchronized void  run() {
      try {
        ... some code requiring long time
      } catch(Exception e) {
        ..I want to catch here and send to calling thread
      }
    }
  }

  synchronized(connect) {
    new Thread(connect).start();
    connect.wait();
    ...if exception then handle it
    ...keep on with code if no exception occurred
  }

} catch(Exception e) {
}

The best was is to not use Thread directly, but instead use a Future . 最好的办法是不要直接使用Thread,而要使用Future you can run a FutureTask via a Thread if you desire, or get a Future by submitting a Callable to an Executor (the preferred method). 您可以根据需要通过线程运行FutureTask ,也可以通过将Callable提交给执行程序来获得Future(首选方法)。 the Future gives you a convenient way to wait for the task to complete and to deal with the results (regular or exceptional). “未来”为您提供了一种方便的方式来等待任务完成并处理结果(常规或异常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM