线程专区---第2集intertupt和interrupted和isInterrupted区别

1 isInterrupted

  • 作用 : 判断线程状态是否为中断 
  • 调用方式 :new Thread().isInterrupted()
  • 注意:如果 isInterrupted方法返回的是true,那么就一定是调用了  intertupt ()方法

2 intertupt

  • 作用 : 修改线程状态为 “中断”
  •  调用方式 :new Thread().interrupt();
     

3 interrupted 

  • 作用 : 返回线程目前的中断状态,同时清空状态(即设置状态为 false)
  • 调用方式 :Thread.interrupted()
  • 方法内部代码  public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
/**
 * 1 isInterrupted 用来判断线程的中断状态,如果被中断则 为 ture
 * 2 interrupt() 中断的方法,如果线程处于 无事可做的情况下(例如 sleep 的时候)则可以直接中断线程,否则只改变线程的中断状态
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        a1();
        a2();

    }

    /**
     * 一个线程不管在启动前,还是启动后他的 中断状态都是 false
     * 下面的方法是在线程启动前后分别执行 isInterrupted() 方法,然后得到结果都是false
     *
     * @throws InterruptedException
     */
    public static void a1() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("执行完毕");
        });
        System.out.println(thread.isInterrupted());
        thread.start();
        Thread.sleep(2000);
        System.out.println(thread.isInterrupted());
    }

    /**
     * interrupted()的主要作用是返回现有的中断状态,然后再清除中断状态(即 设置中断状态为 false)
     *
     * @throws InterruptedException
     */
    public static void a2() throws InterruptedException {
        Thread.currentThread().interrupt();
        System.out.println(Thread.interrupted());
        System.out.println(Thread.currentThread().isInterrupted());
        System.out.println(Thread.currentThread().isInterrupted());

    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值