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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值