java中給出一個(gè)子線程如何捕獲主線程異常的例子
馬克-to-win:接著我們看子線程如何捕獲主線程的異常
例:1.5.4_2-本章源碼
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
import java.lang.Thread.UncaughtExceptionHandler;
class ThreadMark_to_win extends Thread {
Thread mainT;
Test test;
ThreadMark_to_win(Thread t1,Test t2)
{
mainT = t1;
test=t2;
mainT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是"+test.name+" "+t.getName()+" "+ e.getMessage());
}
});
}
public void run()
{
for(int i=0;i<3;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println("在子線程"+i);
}
}
}
public class Test {
String name="馬克-to-win在主線程";
public static void main(String[] args) {
Thread mainT = Thread.currentThread();
Test t=new Test();
ThreadMark_to_win tm = new ThreadMark_to_win(mainT,t);
tm.start();
for (int i = 0; i < 3; i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
System.out.println("在主線程" + i);
}
throw new RuntimeException("在主線程,我自己拋出的一個(gè)異常");
}
}
輸出結(jié)果:
在主線程0
在子線程0
在主線程1
在子線程1
在主線程2
在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是馬克-to-win在主線程 main 在主線程,我自己拋出的一個(gè)異常
在子線程2
后續(xù):
馬克-to-win:上面的程序通過(guò)new ThreadMark_to_win(mainT,t);把主線程的參考指針傳進(jìn)了子線程。事實(shí)上,UncaughtExceptionHandler可以不用放在一個(gè)線程中,只要找到一個(gè)類放置就可以了或放置在它自己里面。(以下會(huì)給出一個(gè)例子),但既然找到一個(gè)類放置就可以,我們就可以把他放在另一個(gè)線程(一個(gè)線程就是一個(gè)類)中,達(dá)到別的線程處理當(dāng)前線程的異常的目的。
例:1.5.4_3-本章源碼
import java.lang.Thread.UncaughtExceptionHandler;
class ThreadMark_to_win {
Thread mainT;
Test test;
ThreadMark_to_win(Thread t1,Test t2)
{
mainT = t1;
test=t2;
mainT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是"+test.name+" "
+t.getName()+" "+ e.getMessage());
}
});
}
}
public class Test {
String name="馬克-to-win在主線程";
public static void main(String[] args) {
Thread mainT = Thread.currentThread();
Test t=new Test();
ThreadMark_to_win tm = new ThreadMark_to_win(mainT,t);
for (int i = 0; i < 3; i++)
System.out.println("在主線程" + i);
throw new RuntimeException("在主線程,我自己拋出的一個(gè)異常");
}
}
輸出結(jié)果:
在主線程0
在主線程1
在主線程2
在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是馬克-to-win在主線程 main 在主線程,我自己拋出的一個(gè)異常
例:1.5.4_4
import java.lang.Thread.UncaughtExceptionHandler;
public class Test {
String name="馬克-to-win在主線程";
public static void main(String[] args) {
Thread mainT = Thread.currentThread();
Test t=new Test();
// ThreadMark_to_win tm = new ThreadMark_to_win(mainT,t);
mainT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable e) {
System.out.println("在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是"+t.name+" "
+th.getName()+" "+ e.getMessage());
}
});
for (int i = 0; i < 3; i++)
System.out.println("在主線程" + i);
throw new RuntimeException("在主線程,我自己拋出的一個(gè)異常");
}
}
結(jié)果:
在主線程0
在主線程1
在主線程2
在子程序處理呢, 傳進(jìn)來(lái)的參數(shù)是馬克-to-win在主線程 main 在主線程,我自己拋出的一個(gè)異常