今天在测试环境通过线程池执行任务时突然被中断,跟踪日志发现代码跑到一半后面的日志就不再打印,而且也没有任何异常堆栈信息,也就是说程序执行被中断了,后面反复尝试经排查发现是线程池使用不当导致。
我们用线程池执行任务一般有两种方式,一种是不需要返回结果的调用execute方法,一种是需要返回结果的调用submit方法。
@Test
public void test0() {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
System.out.println("子线程-begin");
System.out.println(1 / 0);
System.out.println("子线程-end");
});
System.out.println("主线程执行完成");
}
运行结果如下:有异常堆栈信息
主线程执行完成
子线程-begin
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.zhouyong.practice.executor.ExecutorTest.lambda$test0$0(ExecutorTest.java:20)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Process finished with exit code 0
@Test
public void test1() {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> {
System.out.println("子线程-begin");
System.out.println(1 / 0);
System.out.println("子线程-end");
});
System.out.println("主线程执行完成");
}
执行结果如下:没有异常堆栈信息(异常被吃掉)
子线程-begin
主线程执行完成
Process finished with exit code 0
调用线程池的submit方法执行线程时,异常处理的两种方式:
@Test
public void test2(){
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> {
try {
System.out.println("子线程-begin");
System.out.println(1 / 0);
System.out.println("子线程-end");
} catch (Exception e) {
//TODO 此处做日志记录或者打印异常堆栈
e.printStackTrace();
}
});
System.out.println("主线程执行完成");
}
运行结果:
通过调用submit的返回值Future的get方法时会阻塞等待线程执行完成,如果有异常会抛出
@Test
public void test2() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<?> future = executorService.submit(() -> {
System.out.println("子线程-begin");
System.out.println(1 / 0);
System.out.println("子线程-end");
});
//TODO 调用get方法时会等待线程执行,如果有异常会抛出,此处可以catch异常做日志记录
//由于get方法会阻塞主线程,因此最好也放在线程池中执行(调用execute方法即可)
System.out.println(future.get());
System.out.println("主线程执行完成");
}
运行结果如下:
由于feture.get()方法会阻塞主线程,因此最好通过线程池执行
@Test
public void test4() {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<?> future = executorService.submit(() -> {
System.out.println("子线程-begin");
System.out.println(1 / 0);
System.out.println("子线程-end");
});
//由于get方法会阻塞主线程,因此最好也放在线程池中执行(调用execute方法即可)
executorService.execute(()-> {
try {
future.get();
} catch (Exception e) {
//TODO 此处做日志记录或者打印异常堆栈
e.printStackTrace();
}
});
System.out.println("主线程执行完成");
}
运行结果如下: