课程素材来自 http://enjoy.ke.qq.com/ 版权所有
java线程中,线程中断方法详解:
线程自然终止:自然执行完或抛出未处理异常
stop(),resume(),suspend()已不建议使用,stop()会导致线程不会正确释放资源,suspend()容易导致死锁。
java线程是协作式,而非抢占式
调用一个线程的interrupt() 方法中断一个线程,并不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定。
isInterrupted() 判定当前线程是否处于中断状态。
static方法interrupted() 判定当前线程是否处于中断状态,同时中断标志位改为false。
方法里如果抛出InterruptedException,线程的中断标志位会被复位成false,如果确实是需要中断线程,要求我们自己在catch语句块里再次调用interrupt()。
此处关于线程的sleep方法为什么会抛出中断异常InterruptedException
看代码吧
package com.hw.ch1; /** * Created by Administrator on 2018/5/8. */ public class HasInterrputException { private static class UseThread extends Thread{ public UseThread(String name){ super(name); } @Override public void run() { while (!isInterrupted()){ try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("the flag is "+isInterrupted()); e.printStackTrace(); interrupt(); System.out.println("the flag2 is "+isInterrupted()); } } } // 线程调用sleep方法后进入sleep状态,而sleep方法中java在实现的时候支持对中断标志位的检查, // 一旦sleep方法检查到了中断标志位为true,就会终止sleep,并抛出这个InterruptedException。 // 方法里如果抛出InterruptedException, // 线程的中断标志位会被复位成false,如果确定是需要中断线程, // 要求我们自己在catch语句块里再次调用interrupt() // InterruptedException表示一个阻塞被中断了,阻塞包括sleep(),wait() public static void main(String[] args) throws InterruptedException { Thread endThread = new UseThread("HasInterrputEx"); endThread.start(); Thread.sleep(500); // 为什么加上Thread.sleep(500),就会有异常发生,注释掉就没有呢 // 因为调用interrupt的时候,子线程甚至还么来的及初始化完成 endThread.interrupt(); } } }