7.多线程学习--处理线程的不受控制异常

时间:2022-05-30 00:45:00
package com.jackson.deng.concurrent.chapter1.seven;

import java.lang.Thread.UncaughtExceptionHandler;

/**
* 处理线程的不受控制异常
*
* @author jackson
*
*/
public class ProcessNotCaughtException {

/**
* function desc : 模拟一个出问题的task
*/
public class Task implements Runnable {
@Override
public void run() {
new Integer("TTT");
}
}

/**
* function desc:可以在这里对自定义不收控制异常线程的信息进行处理<br>
* 一般记录日志
*/
public class ExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("An exception has been captured\n");
System.out.printf("Thread: %s\n", t.getId());
System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
System.out.printf("Stack Trace: \n");
e.printStackTrace(System.out);
System.out.printf("Thread status: %s\n", t.getState());
}
}

public static void main(String[] args) {
ProcessNotCaughtException pnce = new ProcessNotCaughtException();
Thread thread = new Thread(pnce.new Task());
thread.setUncaughtExceptionHandler(pnce.new ExceptionHandler());
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The thread has finished");
}
}

运行结果:

An exception has been captured
Thread: 8
Exception: java.lang.NumberFormatException: For input string: "TTT"
Stack Trace: 
java.lang.NumberFormatException: For input string: "TTT"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.<init>(Integer.java:677)
at com.jackson.deng.concurrent.chapter1.seven.ProcessNotCaughtException$Task.run(ProcessNotCaughtException.java:19)
at java.lang.Thread.run(Thread.java:745)
Thread status: RUNNABLE
The thread has finished