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

这一章节我们来讨论一下线程的停止,由于线程的停止方法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

你可能感兴趣的:(多线程,从头认识多线程)