从头认识java-17.2 线程中断(interrupt)

来源:互联网 发布:松下触摸屏软件说明书 编辑:程序博客网 时间:2024/06/06 12:53

这一章节我们来讨论一下线程中断(interrupt)。

1.什么是线程中断(interrupt)?

就是在多线程运行的时候,我们给线程贴上一个中断的标记,但是不要求线程终止。

 

2.例子:

中断的例子:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();}i++;}}}


输出:

PrintA
PrintA
PrintA

不中断的例子:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintB printB = new PrintB();Thread threadB = new Thread(printB);threadB.start();}}class PrintB implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("PrintB");Thread.currentThread().interrupt();}}}


输出:

PrintB
PrintB
PrintB
PrintB
PrintB

由上面的两个例子我们可以看出,interrupt只是贴上一个中断的标记,不会强制中断。

 

3.interrupt与sleep的冲突

因为当使用sleep在interrupt之后使用,sleep将会去掉interrupt这个标记

冲突代码,下面的代码将会无限输出:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();try {Thread.currentThread().sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}i++;}}}


总结:这一章节主要介绍线程中断(interrupt)。

 

这一章节就到这里,谢谢。

-----------------------------------

目录

 

2 0
原创粉丝点击