publicstaticvoidmain(String[] args){ // 手动创建线程池 ExecutorService threadPool = createThreadPool(); try { // 调用 submit() 方法提交任务,默认会吞掉异常,改写后可以抛出异常了 threadPool.submit(() -> { System.out.println(Thread.currentThread().getName() + "\t" + "进入 submit() 方法 ---start"); for (int i = 1; i <= 4; i++) { if (i == 3) { int age = 10 / 0; } System.out.println("come in execute: " + i); } System.out.println(Thread.currentThread().getName() + "\t" + "进入 submit() 方法 ---end"); }); } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } }
...... }
程序执行的输出结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
pool-1-thread-1 进入 submit() 方法 ---start come in execute: 1 come in execute: 2 16:11:12.103 [pool-1-thread-1] ERROR com.java.interview.pool.ThreadPoolDemo - java.lang.ArithmeticException: / by zero java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at com.java.interview.pool.ThreadPoolDemo$1.afterExecute(ThreadPoolDemo.java:113) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1129) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.lang.ArithmeticException: / by zero at com.java.interview.pool.ThreadPoolDemo.lambda$test02$1(ThreadPoolDemo.java:55) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ... 2 common frames omitted