可设置未捕获异常的处理类,处理在线程组中任一线程抛出的未捕获的异常。
本节的示例代码在 com.elanzone.books.noteeg.chpt1.sect12 package中
自定义线程组 (MyThreadGroup)
public class MyThreadGroup extends ThreadGroup
@Override public void uncaughtException(Thread t, Throwable e) { System.out.printf("The thread %s has thrown an Exception\n",t.getId()); e.printStackTrace(System.out); System.out.printf("Terminating the rest of the Threads\n"); interrupt(); }
线程类 (Task)
float result; Random random = new Random(Thread.currentThread().getId()); while (true) { result = 1000 / ((int) (random.nextDouble() * 1000)); System.out.printf("%d : %f\n", Thread.currentThread().getId(), result); if (Thread.currentThread().isInterrupted()) { System.out.printf("%d : Interrupted\n", Thread.currentThread().getId()); return; } }
控制类 (Main)
MyThreadGroup threadGroup = new MyThreadGroup("MyThreadGroup"); Task task = new Task();
for (int i = 0; i < 20; i++) { Thread thread = new Thread(threadGroup, task); thread.start(); }