public static native void sleep(long millis) throws InterruptedException

Thread.sleep()方法会抛出一个InterruptedException中断异常,当抛出此异常时,当前线程的中断状态将被清除。

所以需要我们在程序中捕获并且处理它。

public class InterruptDemo {

    public static void main(String[] args) throws InterruptedException {

        Thread t = new Thread(){
            public void run() {
                while(true){
                    // 如果此处不手工增加线程中断的处理逻辑,外部发送中断消息,线程也会依旧照样执行
                    if( Thread.currentThread().isInterrupted() ){
                        System.out.println( "Interrupted");
                        break;
                    }

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                        /*
                         * sleep()方法由于中断抛出异常,此时,它会清楚中断标记,这样在下一次循环开始时,就无法再次捕获到这个中断,
                         * 所以在此处的异常处理中,必须再次设置中断标记位
                         */
                        Thread.currentThread().interrupt();
                    }

                }
            };
        };
        t.start();
        Thread.sleep(2000);
        t.interrupt();    
    }

}

运行这段代码,第一次会抛出java.lang.InterruptedException: sleep interrupted,线程进行第二次的循环时,执行 break;

通常还可以使用枚举类 java.util.concurrent.TimeUnit 的sleep()方法,这是将时间参数转换为Thread.sleep方法所需格式的一种便捷方法。

 TimeUnit.SECONDS.sleep(100);

results matching ""

    No results matching ""