work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何中断线程

Posted on 2019-12-29 16:52  work hard work smart  阅读(292)  评论(0编辑  收藏  举报

如何中断线程

目前使用的方法

调用interrupt(), 通知线程应该中断了

1) 如果线程处于被阻塞状态,那么线程将立即退出被阻塞状态,并抛出一个InterruptException异常

2) 如果线程处于正常状态,那么会将该线程的中断标志置为true。 被设置中断标志的线程将继续运行,不受影响

如下面的代码

public class InterruptDemo {

    public static void main(String[] args) throws  InterruptedException{
        Runnable interruptTask = new Runnable() {

            int i = 0;
            @Override
            public void run() {

                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(100);
                        i++;
                        System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + " ) loop " + i);
                    }

                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + " ) catch InterruptedException");
                    //e.printStackTrace();
                }



            }
        };
        Thread t1 = new Thread(interruptTask, "t1");
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is new" );

        t1.start();
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is started ");

        Thread.sleep(300);
        t1.interrupt();
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is interrupted ");

        Thread.sleep(300);
        System.out.println(t1.getName() + " (" + t1.getState() + " ) is interrupted  now");

    }

}

  打印结果如下:

t1 (NEW ) is new
t1 (RUNNABLE ) is started 
t1 (RUNNABLE ) loop 1
t1 (RUNNABLE ) loop 2
t1 (RUNNABLE ) loop 3
t1 (RUNNABLE ) is interrupted 
t1 (TERMINATED ) is interrupted  now

  当调用interrupt的时候,线程正在执行sleep( Thread.sleep(100);),抛出异常。