线程的中断
01强制性中断:
线程的暂时:suspend()
恢复:resume()
停止:stop()
以上为旧有线程Thread API中的内容,因在调用后,线程不会释放已占有资源(锁),已发生死锁等现象已不建议使用。
02协同式中断:
interrupt 方法 :设置中断标识位,对线程进行中断尝试
isinterrupted : 返回Boolean 类型 ,显示当前线程是否被中断的状态
interrupted 方法:检查 并 清除中断标识位 调用完该方法之后 使 isinterrupted 为false
package cn.test.Thead;
public class endThead {
private static class UseThead extends Thread{
public UseThead (String name){
super(name);
}
@Override
public void run() {
String threadName = Thread.currentThread().getName(); //获取当前线程.name
System.out.println(threadName+"开始状态 interrupt flag :"+isInterrupted()); //开始状态
//while ( ! isInterrupted()){
while (! interrupted()){
System.out.println(threadName+" is running");
System.out.println(threadName+"运行状态 interrupt flag=" + isInterrupted() );
}
System.out.println( "最终状态 "+isInterrupted());
//super.run();
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThead("endThread");
endThread.start(); //开启线程
Thread.sleep(10); // 线程睡眠 但是 interrupt 仍然会被侦测
// System.out.println("sss");
endThread.interrupt();
}
}
}
拓展:阻塞方法中抛出InterruptedException异常后,如果需要继续中断,需要手动再中断一次
留给程序员做 干预时间,手短判断是否要中断线程。
/**
*类说明:阻塞方法中抛出InterruptedException异常后,如果需要继续中断,需要手动再中断一次
*/
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(Thread.currentThread().getName()
+" in InterruptedException interrupt flag is "
+isInterrupted());
interrupt(); //手动资源释放 需要时执行
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " I am extends Thread.");
}
System.out.println(Thread.currentThread().getName()
+" interrupt flag is "+isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThread("HasInterrputEx");
endThread.start();
Thread.sleep(500);
endThread.interrupt();
}
}
补充:死锁状态线程不会理会中断