因为java在写多线程并发程序的时候,线程执行过程中出现异常需要马上处理执行相应逻辑,可使用ThreadFactory类来解决。
例子:
ExecutorService executor = Executors.newSingleThreadExecutor(new ExceptionThreadFactory());
executor.submit(new Runnable() {
@Override
public void run() {
throws new RuntimeException();
}
});
public class ExceptionThreadFactory implements ThreadFactory
{
@Override
public Thread newThread(Runnable r)
{
Thread t = new FastThreadLocalThread(r);
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
doLog();
doSomeString();
}
});
return t;
}
}
ps: 推荐用netty的FastThreadLocalThread性能更好