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

本文介绍了线程中断的概念,通过两个示例对比了中断与不中断的区别,并探讨了interrupt与sleep结合使用时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这一章节我们来讨论一下线程中断(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)。

 

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

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

目录

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值