JAVA并发,线程异常捕获

时间:2023-03-08 20:06:07

由于线程的特性,当我们启动了线程是没有办法用try catch捕获异常的,如下例:

 package com.xt.thinks21_2;

 import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 线程异常捕获测试
*
* @author xue
*
*/
public class ThreadUncaughtExceptionTest implements Runnable { @Override
public void run() {
// TODO Auto-generated method stub
throw new NullPointerException();
} public static void main(String[] args) {
try {
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadUncaughtExceptionTest());
es.shutdown();
// or this
// Thread t = new Thread(new ThreadUncaughtExceptionTest());
// t.start();
} catch (Exception e) {
// TODO: handle exception
} }
}

打印异常信息为:

Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at com.xt.thinks21_2.ThreadUncaughtExceptionTest.run(ThreadUncaughtExceptionTest.java:17)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

此时,我们需要为线程定制工厂类来生产线程,为线程指定UncaughtExceptionHandler

 package com.xt.thinks21_2;

 import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory; /**
* 未捕获异常执行程序
*
* @author Administrator
*
*/
class ThreadUncaughtExceptionHandler implements UncaughtExceptionHandler { @Override
public void uncaughtException(Thread t, Throwable e) {
// TODO Auto-generated method stub
System.out.println("caught:" + e);
} } /**
* 线程工厂
*
* @author Administrator
*
*/
class HandlerThreadExceptionFactory implements ThreadFactory { @Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(new ThreadUncaughtExceptionHandler());
return t;
} } /**
* 线程异常捕获测试
*
* @author xue
*
*/
public class ThreadUncaughtExceptionTest implements Runnable { @Override
public void run() {
// TODO Auto-generated method stub
throw new NullPointerException();
} public static void main(String[] args) {
ExecutorService es = Executors
.newCachedThreadPool(new HandlerThreadExceptionFactory());
es.execute(new ThreadUncaughtExceptionTest());
es.shutdown();
}
}

此时,我们就可以看到异常信息被捕获到了:

caught:java.lang.NullPointerException