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