注:此文为学习《疯狂Java讲义》的笔记,因此内容全部来自于该书中。
1.线程组
ThreadGroup表示线程组,可以对一批线程进行分类管理。对线程组的控制相当于同时控制这批线程。用户创建的所有现场都属于指定线程组,如果没有指定,则线程数与默认线程组。默认情况下,子线程和创建它的父线程属于同一个线程组。线程运行中途不能改变它所属的线程组。
一旦某个线程加入了指定线程组之后,该线程将一直属于该线程组,直到该线程死亡,线程运行中不能改变它所属的线程组。
Thread类中相关构造方法。
Thread Allocates a new |
Thread Allocates a new |
Thread Allocates a new |
Thread Allocates a new |
ThreadGroup类的构造方法。
Constructor and Description |
ThreadGroup Constructs a new thread group. |
ThreadGroup Creates a new thread group. |
ThreadGroup方法。
Modifier and Type | Method and Description |
| Returns an estimate of the number of active threads in this thread group and its subgroups. |
| Returns an estimate of the number of active groups in this thread group and its subgroups. |
| Returns the maximum priority of this thread group. |
| Interrupts all threads in this thread group. |
| isDaemon Tests if this thread group is a daemon thread group. |
| Tests if this thread group has been destroyed. |
| setDaemon Changes the daemon status of this thread group. |
| setMaxPriority Sets the maximum priority of the group. |
| uncaughtException Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific |
2.未处理的异常
如果线程执行过程中抛出了一个未处理异常,JVM在结束该线程之前自动查找是否有对应的UncaughtExceptionHandler对象,如果找到该处理器对象,调用该对象的uncaughtException(Thread t,Throwable e)方法处理异常。
Thread.UncaughtExceptionHandler是Thread类一个内部接口,只有一个方法,即voiduncaughtException()。
Thread类中设置异常处理器的方法如下。
Modifier and Type | Method and Description | |
| setDefaultUncaughtExceptionHandler Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread. | |
| setUncaughtExceptionHandler Set the handler invoked when this thread abruptly terminates due to an uncaught exception. |
ThreadGroup实现了Thread.UncaughtExceptionHandler接口。线程组会作为默认异常处理器。当一个线程抛出异常,JVM首先查找该异常对应的异常处理器,如果找到则调用该异常处理器处理该异常;否则JVM将会调用该线程组对象的uncaughtException()方法来处理该异常。
线程组处理异常的默认流程。(1)如果该线程组有父线程组,则调用父线程组的uncaughtException()方法来处理该异常。(2)如果该线程实例所属的线程类有默认的异常处理器,那么调用该异常处理器来处理该异常。(3)如果该异常对象时ThreadDeath的对象,则不做任何处理,否则,将异常跟踪栈的信息打印到System.err输出流,并结束该线程。