实现了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();//此处启动线程,异常怎么处理?
}
}
顺便请讲一下,线程的异常处理./**
* 实现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...捕获),将捕获到的异常加入这个异常列表 然后异常处理线程就可以处理这个异常了
synchronized(this){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
int a = 1/0;
}
}
public void run(){
try{
Thread.sleep(1000);
test();
}catch(InterruptedException e){
new RuntimeException(e);
}catch(){Exception e){
new RuntimeException(e);
}
}
sleep是睡眠该线程一定时间...将CPU交给其它线程...该线程进入等待池..在你这里也可以不要
try {
do();
} catch (Throwable t) {
bq.add(t);
}
}// 异常处理线程
public void run() {
while (true) {
Throwable t = bq.get(0);
try {
throw t;
} catch (...)
}
}