1.0线程 线程的中断

线程的中断

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();
		

	}

}

补充:死锁状态线程不会理会中断

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值