首页 > 其他 > 详细

interrupt、interrupted和isInterrupted的区别

时间:2017-11-25 20:25:36      阅读:206      评论:0      收藏:0      [点我收藏+]
1、interrupt() 
interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。
注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。
 
2、interrupted() 和 isInterrupted()
public static boolean interrupted () {
    return currentThread().isInterrupted(true);
}
public boolean isInterrupted () {
    return isInterrupted( false);
}
private native boolean isInterrupted( boolean ClearInterrupted);

 

如果这个参数为true,说明返回线程的状态位后,要清掉原来的状态位(恢复成原来情况)。

这个参数为false,就是直接返回线程的状态位。

 

class Example2 extends Thread {
    public static void main(String args[]) throws Exception {
        Example2 thread = new Example2();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Asking thread to stop...");
        // 发出中断请求
        thread.interrupt();
        Thread.sleep(3000);
        System.out.println("Stopping application...");
    }

    public void run() {
        // 每隔一秒检测是否设置了中断标示
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Thread is running...");
            long time = System.currentTimeMillis();
            // 使用while循环模拟 sleep
            while ((System.currentTimeMillis() - time < 1000) ) {
            }
        }
        System.out.println("Thread exiting under request...");
    }
}

 

interrupt、interrupted和isInterrupted的区别

原文:http://www.cnblogs.com/lnas01/p/7896169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!