日期:2014-05-20  浏览次数:20980 次

关于线程run()方法中的异常
实现了Runnable接口的run()方法,但是run()方法中所调用的方法会抛出异常,不想让异常在run()方法中消失,想让他继续抛出,最后在启动线程处捕获,具体请看示例代码.
顺便请讲一下,线程的异常处理.

/**
  *   实现Runnable接口的类SubThread
  */
    public   class   SubThread   implements   Runnable{
          public   void   run(){//编译错误   try..catch..
                  test();//怎样让该方法的异常继续往上抛?
          }
          public   void   test()   throws   Exception   {
                throw   new   Exception( "Thread   Exception! ");
          }
    }
/**
  *   启动线程的类
  */
  public   class   TestSubThread   {
        public   static   void   testST(){
                SubThread   subThread   =   new   SubThread();
                Thread   thread   =   new   Thread(subThread);
                thread.start();//此处启动线程,异常怎么处理?
        }
  }

------解决方案--------------------
不同线程的函数调用堆栈是不同的 所以直接实现你的想法是不可能的
你可以变通一下 做一个异常处理的后台线程 循环监听一个一个异常列表 当其他线程中有异常出现时(通过在线程的run函数中加try..catch...捕获),将捕获到的异常加入这个异常列表 然后异常处理线程就可以处理这个异常了
------解决方案--------------------
public void run(){
synchronized(this){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
int a = 1/0;
}
}
------解决方案--------------------
请大家到我的计算机论坛看看,随便给提点意见,人多力量大嘛,注册一下,回答几个一直我都不会的问题,肯定我会给大家奖励的,网址是,http://java.cc.topzj.com/
------解决方案--------------------
BlockingQueue bq; // 当队列为空时 get 将等待。示意代码。

public void run() {
try {
do();
} catch (Throwable t) {
bq.add(t);
}
}

// 异常处理线程
public void run() {
while (true) {
Throwable t = bq.get(0);
try {
throw t;
} catch (...)
}
}