中断含有死循环和sleep的子线程(java.lang.InterruptedException: sleep interrupted)

【转载】:https://blog.csdn.net/qq_33291307/article/details/78804781

死循环线程中包含sleep,无法中断线程:在sleep前面添加Thread.current.isInterrupt判断,跳出死循环,因为sleep本身是抛出一个interrupt异常。我觉得转载的比较容易理解,注意sleep的位置和if()语句的位置。(忽略我可能写错的方法名)。

java 高并发

问题描述:当前 if 判断的中断`如果在sleep ,就算外面中断,里面也会有序的退出,

但是当if 判断在sleep 后面的时候,他就会出想中断异常 (时间不够造成的 main 也是一个线程)

package com.example.echo.Lock;

/**
 * Thread写在哪里,当对当前的进程影响
 */

/**
 *
 */
class Interrupted_root_make extends Thread{

    @Override
    public void run() {
        while (true) {
            System.out.println("-----");


            /**
             * 使用中断命令,外部只是其的一个通知命令,实际上的中断的操作还是需要内部自己判断操作,退出
             */
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if ( Thread.currentThread().isInterrupted() ) {
                System.out.println("i has interputed");
                break;
            }

            Thread.yield();
        }
    }
}
public class Interruped_test {
    public static void main(String[] args) throws InterruptedException {
        Interrupted_root_make interrupted_root_make = new Interrupted_root_make();
        interrupted_root_make.start();

        interrupted_root_make.interrupt();




    }
}

正确的

class Interrupted_root_make extends Thread{

    @Override
    public void run() {
        while (true) {

            if ( Thread.currentThread().isInterrupted() ) {
                System.out.println("i has interputed");
                break;
            }
            System.out.println("-----");


            /**
             * 使用中断命令,外部只是其的一个通知命令,实际上的中断的操作还是需要内部自己判断操作,退出
             */
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }



            Thread.yield();
        }
    }
}
public class Interruped_test {
    public static void main(String[] args) throws InterruptedException {
        Interrupted_root_make interrupted_root_make = new Interrupted_root_make();
        interrupted_root_make.start();
        Thread.sleep(1000);
        interrupted_root_make.interrupt();




    }
}

猜你喜欢

转载自blog.csdn.net/qq_37334150/article/details/80588685
今日推荐