您的位置:首页 > 编程语言 > Java开发

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

2017-06-12 17:57 531 查看
这一章节我们来讨论一下线程中断(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;

@Override
public 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 {

@Override
public 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;

@Override
public 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 block
e.printStackTrace();
}
}
i++;
}
}
}

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

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

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

文件夹
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: