线程中断的方式

stop()

强制中断线程,可能导致线程中的资源没有释放,比如在try-catch-finally中释放资源,直接中断,不会调用finally块。

new Thread().interrupte()

         协作式的中断线程,不会强制中断线程,会发一个interrupt的信号,线程run方法中,如果有Thread.sleep()或者wait,捕获了InterruptedException,会命中该catch, 重置interrupt标记位,如果需要处理该标记位,需要显示调用interrupt(),再判断isInterrupted(),判断run方法执行结束(如:在while循环中,break )。

new Thread().isInterrupted()

线程是否中断的标记位

Thread.interrupted()

         静态方法,获取当前线程的中断标记位。调用之后,会重置interrupt标记位,再次通过isInterrupted()获取就为false啦

实战

 

		final Thread thread = new Thread() {
			@Override
			public void run() {
//				while (Thread.interrupted()){
				while (!isInterrupted()){
					System.out.println("Running");
					System.out.println("isInterrupted=" + isInterrupted());
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
						System.out.println("InterruptedException isInterrupted=" + isInterrupted());
						interrupt();
					}
				}
				System.out.println("while end isInterrupted=" + isInterrupted());
			}
		};

		thread.start();
		System.out.println("main");
		try {
			Thread.sleep(30);
			thread.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

            

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值