• 如何中断线程


    如何中断线程

    目前使用的方法

    调用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);),抛出异常。

  • 相关阅读:
    Phpstorm+Xdebug配置
    ThinkPHP5.0---URL访问
    Thinkphp5创建控制器
    ThinkPHP5.0的安装
    网页动态背景——随鼠标变换的动态线条
    git SSH
    [go] 循环与函数
    svg make a face
    Hello Vizhub
    Beetlsql自定义生成entity,mapper,md代码
  • 原文地址:https://www.cnblogs.com/linlf03/p/12115445.html
Copyright © 2020-2023  润新知