java.lang.InterruptedException: sleep interrupted

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();




    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值