java interrupt理解

来源:互联网 发布:数控编程员招聘 编辑:程序博客网 时间:2024/05/21 10:56

理解

 当一个线程被阻塞的时候(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...falseThread is running...trueThread is running...trueThread is running...trueThread 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
原创粉丝点击