Thread.interrupted()方法的陷阱

本文详细解析了Java中线程中断的两种不同方法及其行为差异。通过具体代码示例,展示了Thread.currentThread().interrupt()与Thread.interrupted()及Thread.currentThread().isInterrupted()的区别,解释了为何后者能保留中断状态。
package test84;

public class selfInterrupt {

public static void main(String[] args) {
Thread.currentThread().interrupt();
//  下面的判断会打印出来这样的语句 Interrupt:false
//  这样的结果是不是很让人费解呢???
//  
//  分析其原因为:
//  
//  因为在上面的一句代码可以中断线程,所以if判断线程是否中断就会得到的事true
//  但是 Thread.interrupted()这个方法执行完后就会清除线程的中断状态,
//  所以最后再次的打印Thread.interrupted()方法就会得到false结果。
if(Thread.interrupted())
System.out.println("Interrupted:"+ Thread.interrupted());
else
{
System.out.println("Not Interrupted"+Thread.interrupted());
}
//  如果用下面的这个方法来进行if判断就会出现那种情况了,
//  Thread.currentThread().isInterrupted();这个方法得到的结果:Interrupt:true
//  
//  因为它判断完后就不会清除线程的中断状态,只是返回一个线程状态的结果
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值