Thread.interrupt()的使用

    Thread.interrupt()简单从名称来看就是打断线程,那么到底是如何打断线程的,有什么限制条件?我们今天来讨论一下这个问题
  首先我们看一下jdk上面的解释


If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}.

    从代码上面的注释来看,如果在线程中由于Object.wait(),Thread.join()等方法造成阻塞,然后被打断,那么就会清除掉状态。因此我们猜测Thread.interrupt()向操作系统发出一个中断信号,设置中断标志,在操作系统合适的时候,检测中断标志,如果确实要求中断,那么就中断该线程。但是由于Object.wait()、Thread.join()的过程中该线程被中断,那么就会清除掉中断标志,那么就无法检测到相应中断标志,因此会导致该线程继续运行,接下来我们来进行验证:


public class InterrupteTest {
    private static Thread   thread  = null;

    public static void main(String args[]) throws InterruptedException {
        thread = new Thread( new MyThread() );
        thread.start();
        Thread.sleep( 10 );
        thread.interrupt();
        System.out.println( "Interrupted Thread!" );
    }

    static class MyThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                System.out.println( "I am running!" );
                try {
                    Thread.sleep( 1000 );
                } catch (InterruptedException e) {
                }

            }
        }
    }

}

    当我们运行该程序的时候,我们会发现真的无法终止这个线程。那么我们如何真正终止该线程呢?
我们看下面的代码:


public class InterrupteTest {
    private static Thread   thread  = null;

    public static void main(String args[]) throws InterruptedException {
        thread = new Thread( new MyThread() );
        thread.start();
        Thread.sleep( 10 );
        thread.interrupt();
        System.out.println( "Interrupted Thread!" );
    }

    static class MyThread implements Runnable {
        @Override
        public void run() {
            while (!thread.isInterrupted()) {
                System.out.println( "I am running!" );
                try {
                    Thread.sleep( 1000 );
                } catch (InterruptedException e) {
                     thread.interrupt();
                }

            }
        }
    }

}

    运行上面的代码我们会发现上面,我们会发现线程正确的关闭了,当在线程睡眠的过程中,被打断后,会抛出InterruptedException,我们重新通过Thread.interrupt()重新设置线程的中断标志,那么线程在判断thread.isInterrupted()就会返回true了,自然就会退出线程了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值