java interrupt理解

理解

 当一个线程被阻塞的时候(io, sleep等),我们取消这种阻塞,这个时候就可以使用interrupt 

例子和讲解

我们先看个例子,代码入下:


package com.renzhan;

class TestRunnable implements Runnable{
    public void run(){
        while(true)
        {
            System.out.println( "Thread is running..." );

            System.out.println(Thread.currentThread().isInterrupted());
            long time = System.currentTimeMillis();//取系统时间的毫秒数
            while((System.currentTimeMillis()-time < 1000)) {
                //程序循环1秒钟,不同于sleep(1000)会阻塞进程。
            }
        }
    }
}

public class App{
    public static void main(String[] args){
        Runnable r=new TestRunnable();
        Thread th1=new Thread(r);
        th1.start();
        th1.interrupt();
    }
}

代码的输出如下:

Thread is running...
false
Thread is running...
true
Thread is running...
true
Thread is running...
true
Thread is running...
true

线程在调用interrupt 后,只是修改了他的状态,对线程的工作还是没有影响,这个是线程一直占据了cpu处于执行的状态。那么我们把线程的状态修改成sleep呢?
代码如下:

class TestRunnable implements Runnable{
    public void run(){
        try{
            Thread.sleep(1000000); //这个线程将被阻塞1000秒
        }catch(InterruptedException e){
            e.printStackTrace();
            //do more work and return.
        }
    }
}

对应的输出如下:

java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at TestRunnable.run(App.java:6)
    at java.lang.Thread.run(Thread.java:745)

这个是因为线程当前处于阻塞状态,线程没有占用CPU,线程是不可能给自己的中断状态置位的。我们调用intrrupted 时候,这就会产生一个InterruptedException异常。正常我们就可以在异常处理中进行后续逻辑处理,我们也因此让进程变成了非阻塞状态。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值