|
| 1 | +package com.brianway.learning.java.concurrent; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutorService; |
| 4 | +import java.util.concurrent.Executors; |
| 5 | +import java.util.concurrent.ThreadFactory; |
| 6 | + |
| 7 | +/** |
| 8 | + * TODO 为什么有两个线程? |
| 9 | + */ |
| 10 | +public class CaptureUncaughtException { |
| 11 | + public static void main(String[] args) { |
| 12 | + ExecutorService exec = Executors.newCachedThreadPool( |
| 13 | + new HandlerThreadFactory()); |
| 14 | + exec.execute(new ExceptionThread()); |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +class ExceptionThread implements Runnable { |
| 19 | + public void run() { |
| 20 | + Thread t = Thread.currentThread(); |
| 21 | + System.out.println("run() by " + t); |
| 22 | + System.out.println( |
| 23 | + "eh = " + t.getUncaughtExceptionHandler()); |
| 24 | + throw new RuntimeException(); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { |
| 29 | + public void uncaughtException(Thread t, Throwable e) { |
| 30 | + System.out.println("caught " + e + " in " + t); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +class HandlerThreadFactory implements ThreadFactory { |
| 35 | + public Thread newThread(Runnable r) { |
| 36 | + System.out.println(this + " creating new Thread"); |
| 37 | + Thread t = new Thread(r); |
| 38 | + System.out.println("created " + t); |
| 39 | + t.setUncaughtExceptionHandler( |
| 40 | + new MyUncaughtExceptionHandler()); |
| 41 | + System.out.println( |
| 42 | + "eh = " + t.getUncaughtExceptionHandler()); |
| 43 | + return t; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +/* Output: (90% match) |
| 50 | +com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread |
| 51 | +created Thread[Thread-0,5,main] |
| 52 | +eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e |
| 53 | +run() by Thread[Thread-0,5,main] |
| 54 | +eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e |
| 55 | +com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread |
| 56 | +created Thread[Thread-1,5,main] |
| 57 | +eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@3ff961b5 |
| 58 | +caught java.lang.RuntimeException in Thread[Thread-0,5,main] |
| 59 | +*///:~ |
0 commit comments