isInterrupted(),interrupted(),interrupt() 三个方法的联系和区别

package com.demo.concurrent.thread;

/**
 * 线程中断:线程间协作的一种方式
 * 
 * interrupt() 方法:中断标志,设置中断标志为true,等待线程自行停止。
 * 
 * isinterrupted()方法:判断是否中断,如果中断,则返回true,否则返回false
 * 
 * 重要:
 * interrupted()方法:判断是否中断,并清除中断标志。他是一个静态方法,表示的是当前线程的中断状态。
 * threada.interrupted() 等价于 Thread.interrupted();
 * 
 * @author 
 *
 */
public class ThreadInterrupt implements Runnable{

    public void run() {
        //返回true 表明当前线程已经被interrupted
        System.out.println("4:"+Thread.currentThread().isInterrupted());
        
        //返回true 表明当前线程已经被interrupted
        System.out.println("5:"+Thread.interrupted()); 
        
        for(int i=0;i<1000000000;i++) {
            
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread threada = new Thread(new ThreadInterrupt());
        threada.start();
        
        threada.interrupt();
        
        //返回true,表明当前线程已经被interrupted
        System.out.println("1:"+threada.isInterrupted());
        
        //返回false ,表明当前主线程未被interrupted
        System.out.println("2:"+threada.interrupted());
        
        //返回false。因为在内部调用了interrupted方法,之后中断标志被清除
        System.out.println("3:"+threada.isInterrupted());
    }
}

 

执行结果:

1:true
4:true
2:false
5:true
3:false

注意:执行结果有不确定性,因为,主线程和子线程,在同时工作,结果会因为两个线程的执行速度的不通而不同

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值