我是靠谱客的博主 哭泣月光,这篇文章主要介绍java中线程的中断与终止,现在分享给大家,希望可以做个参考。

线程的中断与终止

1、interrupt()isInterrupted()interrupted()的作用

中断就是线程的一个标识位,它表示一个运行中的线程是否被其他线程调用了中断操作,其他线程可以通过调用线程的interrupt()方法对其进行中断操作,线程可以通过调用isInterrupted()方法判断是否被中断,线程也可以通过调用Threadinterrupted()静态方法对当前线程的中断标识位进行复位。

相关视频教程推荐:java在线视频

注意:不要认为调用了线程的interrupt()方法,该线程就会停止,它只是做了一个标志位。

如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class InterruptThread extends Thread{ @Override public void run() { //一个死循环 while (true){ System.out.println("InterruptThread正在执行"); } } } public static void main(String[] args) throws InterruptedException { InterruptThread interruptThread = new InterruptThread(); interruptThread.start(); interruptThread.interrupt();//调用线程的interrupt() System.out.println("interruptThread是否被中断,interrupt = " + interruptThread.isInterrupted()); //此时isInterrupted()方法返回true } 输出结果: interruptThread是否被中断,interrupt = true InterruptThread正在执行 InterruptThread正在执行 InterruptThread正在执行 //...
登录后复制

可以看到当你调用了线程的interrupt()方法后,此时调用isInterrupted()方法会返回true,但是该线程还是会继续执行下去。所以怎么样才能终止一个线程的运行呢?

2、终止线程的运行

一个线程正常执行完run方法之后会自动结束,如果在运行过程中发生异常也会提前结束;所以利用这两种情况,我们还可以通过以下三种种方式安全的终止运行中的线程:

2.1、利用中断标志位

前面讲到的中断操作就可以用来取消线程任务,如下:

复制代码
1
2
3
4
5
6
7
8
public class InterruptThread extends Thread{ @Override public void run() { while (!isInterrupted()){//利用中断标记位 System.out.println("InterruptThread正在执行"); } } }
登录后复制

当不需要运行InterruptThread线程时,通过调用InterruptThread.interrupt()使得isInterrupted()返回true,就可以让线程退出循环,正常执行完毕之后自动结束。

2.2、利用一个boolean变量

利用一个boolean变量和上述方法同理,如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class InterruptThread extends Thread{ private volatile boolean isCancel; @Override public void run() { while (!isCancel){//利用boolean变量 System.out.println("InterruptThread正在执行"); } } public void cancel(){ isCancel = true; } }
登录后复制

当不需要运行InterruptThread线程时,通过调用InterruptThread.cancel()使isCancel等于true,就可以让线程退出循环,正常执行完毕之后自动结束,这里要注意boolean变量要用volatile修饰保证内存的可见性。

2.3、响应InterruptedException

通过调用一个线程的 interrupt() 来中断该线程时,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException,从而提前结束该线程,例如当你调用Thread.sleep()方法时,通常会让你捕获一个InterruptedException异常,如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
public class InterruptThread extends Thread{ @Override public void run() { try{ while (true){ Thread.sleep(100);//Thread.sleep会抛出InterruptedException System.out.println("InterruptThread正在执行"); } }catch (InterruptedException e){ e.printStackTrace(); } } }
登录后复制

当不需要运行InterruptThread线程时,通过调用InterruptThread.interrupt()使得 Thread.sleep() 抛出InterruptedException,就可以让线程退出循环,提前结束。在抛出InterruptedException异常之前,JVM会把中断标识位复位,此时调用线程的isInterrupted()方法将会返回false。

java相关文章教程推荐:java编程入门

以上就是java中线程的中断与终止的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是哭泣月光最近收集整理的关于java中线程的中断与终止的全部内容,更多相关java中线程内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(118)

评论列表共有 0 条评论

立即
投稿
返回
顶部