自然结束
要么是run执行完成了,要么是抛出了一个未处理的异常导致线程提前结束。
API方式
- suspend(): 挂起线程
- resume(): 激活线程
- stop(): 中断线程
但是这些API是过期的,也就是不建议使用的。
不建议使用的原因主要有:以suspend()方法为例,在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。
同样,stop()方法在终结一个线程时不会保证线程的资源正常释放,通常是没有给予线程完成资源释放工作的机会,因此会导致程序可能工作在不确定状态下。
正因为suspend()、resume()和stop()方法带来的副作用,这些方法才被标注为不建议使用的过期方法。
通知中断
interrupt()
通知线程中断
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
Thread thread = new Thread(() -> {
Thread ct = Thread.currentThread();
while (!ct.isInterrupted()) {
}
System.out.println(ct.getName()+"被中断了");
});
thread.start();
System.out.println("输入任意键中断");
System.in.read();
thread.interrupt();
}
isInterrupted()
判断线程是否被中断
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
}
System.out.println("中断了");
});
thread.start();
System.out.println("输入任意键中断线程");
System.in.read();
thread.interrupt();
}
Thread#interrupted()
测试是否中断线程,如果当前线程是中断状态,会清除当前线程的中断标志,重新让当前线程状态为正常状态。
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
}
System.out.println("第一次状态:"+Thread.interrupted());
System.out.println("第二次状态:"+Thread.interrupted());
});
thread.start();
System.out.println("输入任意键查看线程状态");
System.in.read();
thread.interrupt();
}
}