java if interrupted_Java中interrupted()和isInterrupted()之间的区别

interrupted()和isInterrupted()

在这里,我们将看到如何isInterrupted()不同于interrupted()在Java中?

isInterrupted()此方法在java.lang包中可用。

这是非静态方法,因此可通过类对象访问此方法。

此方法用于检查线程是否已被中断。

此方法的返回类型为boolean,因此如果线程已中断,则返回true,否则返回false。

对于isInterrupted()方法,我们需要注意的是,如果线程已被中断,则此方法返回true,然后在中断之后不再将布尔变量设置为false,就像interrupted()方法否则返回false一样。

该方法的语法如下:public boolean isInterrupted(){

}

示例/*我们将使用Thread类方法,因此我们将导入包

但这不是强制性的,因为它是默认导入的

*/

import java.lang.Thread;

class InterruptedThread extends Thread {

//覆盖run()  Thread类的方法

public void run() {

for (int i = 0; i <= 3; ++i) {

/*  通过使用interrupted()方法检查此线程是否

无论是否中断,它都将返回并执行

中断的代码

*/

if (Thread.currentThread().isInterrupted()) {

System.out.println("Is the thread" + Thread.currentThread().getName() + "has been interrupted: " +  Thread.currentThread().isInterrupted());

} else {

System.out.println("Is the thread" + Thread.currentThread().getName() + "has been interrupted: " +  Thread.currentThread().isInterrupted());

}

}

}

public static void main(String args[]) {

InterruptedThread it1 = new InterruptedThread();

InterruptedThread it2 = new InterruptedThread();

/*  使用start()方法调用Thread类的run()方法

线程类start()将调用

InterruptedThread类

*/

it2.start();

it2.interrupt();

it1.start();

}

}

输出结果E:\Programs>javac InterruptedThread.java

E:\Programs>java InterruptedThread

Is the threadThread-1 has been interrupted: true

Is the threadThread-0 has been interrupted: false

Is the threadThread-1 has been interrupted: true

Is the threadThread-1 has been interrupted: true

Is the threadThread-0 has been interrupted: false

Is the threadThread-1 has been interrupted: true

Is the threadThread-0 has been interrupted: false

Is the threadThread-0 has been interrupted: false

在这里,我们将看到如何interrupted()不同于isInterrupted()在Java中?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值