Java多线程
1、不允许抛出受检异常,所以必须自己处理受检异常。
2、类似nullpointExcepiton都会导致当前线程的崩溃
3、但是RuntimeException不可避免,抛出该异常时子线程会结束,但是主线程不会知道,因为主线程通过try catch无法捕获子线程异常。
代码:
package com.eddy.test.threadmgr;
public class TestUncatchException
{
public static class TestRuntimeExceptionThread extends Thread
{
public TestRuntimeExceptionThread()
{
super.setName("thread-TestRuntimeExceptionThread");
}
@Override
public void run()
{
throw new RuntimeException("run time exception");
}
}
public static void main(String[] args)
{
try
{
Thread test = new TestRuntimeExceptionThread();
// 设置线程默认的异常捕获方法
// test.setUncaughtExceptionHandler((Thread t, Throwable e) -> {System.out.println(t.getName() + ": " + e.getMessage());});
test.start();
}
catch(Exception e)
{
System.out.println("catch thread exception");
}
}
}
解决方案:
Thread对象提供了setUncaughtExceptionHandler方法用来获取线程中产生的异常。而且建议使用该方法为线程设置异常捕获方法。