从头认识多线程-1.5 interrupt()和isInterrupt()

本文探讨了Java中线程的停止方法,并重点介绍了interrupt()方法的使用方式及其与isInterrupted()的区别。通过示例代码展示了如何标记线程为中断状态及如何检测这种状态。

这一章节我们来讨论一下线程的停止,由于线程的停止方法stop,suppend,resume已经弃用,因此不推荐,现在只能够使用interrupt,但是这个方法只是标记一下这个线程已经停止,没有实质性的停下来的。

1.代码清单

package com.ray.deepintothread.ch01.topic_5;

public class InterruptSample {
	public static void main(String[] args) throws InterruptedException {
		ThreadFive threadFive = new ThreadFive();
		Thread thread = new Thread(threadFive);
		thread.start();
	}
}

class ThreadFive extends Thread {

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			if (i == 3) {
				Thread.currentThread().interrupt();
			}
			System.out.println("interrupt:" + Thread.currentThread().isInterrupted());

			try {
				sleep(50);
			} catch (InterruptedException e) {
				System.out.println("catch interrupt:" + Thread.currentThread().isInterrupted());
			}
		}
		super.run();

	}
}

输出:

interrupt:false
interrupt:false
interrupt:false
interrupt:true
catch interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false


2.结论

在这里我们先别看catch里面的语句,我们后面将说到这个情况,从其他输出可以看见,interrupt之后,该执行的还是执行,一点改变都没有。


3.在java的方法里面,提供了两个检测中断的方法,下面来对比一下

package com.ray.deepintothread.ch01.topic_5;

public class InterruptSample2 {
	public static void main(String[] args) {
		System.out.println("--------------------------");
		Thread.currentThread().interrupt();
		System.out.println(Thread.interrupted());
		System.out.println(Thread.interrupted());
		System.out.println(Thread.currentThread().isInterrupted());
		System.out.println(Thread.currentThread().isInterrupted());
		System.out.println("--------------------------");
		Thread.currentThread().interrupt();
		System.out.println(Thread.currentThread().isInterrupted());
		System.out.println(Thread.currentThread().isInterrupted());
		System.out.println("--------------------------");
		Thread.currentThread().interrupt();
		System.out.println(Thread.interrupted());
		System.out.println(Thread.interrupted());
	}
}

输出:

--------------------------
true
false
false
false
--------------------------
true
true
--------------------------
true
false


从输出可以看见,interrupted()在检测一次之后就把标记给去掉,但是isInterrupted()却不会去掉这个中断标记。



总结:这一章节我们介绍了interrupt()和isInterrupt(),注意一点,interrupt()是不能够停止线程的。


我的github:https://github.com/raylee2015/DeepIntoThread

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值