java中断

转载csdn文章
https://blog.csdn.net/qpc908694753/article/details/61414495

public class Thread{
  //能中断目标线程
  //调用此方法并不意味着立即停止目标线程正在进行的工作,而只是传递了请求中断状态。
  public void interrupt();
   //返回当前目标线程的中断状态
  public boolean isInterrupted();
  //清除当前线程的中断状态,并返回它之前的值
  public static boolean interrupted();
}

中断,它并不会真正的中断一个正在运行的线程,而只是发出中断请求,然后由线程在下一个合适的时刻中断自己。
Thread.sleep、Object.wait,等都会检测线程合适中断,并在发现中断提前返回。它们在响应中断时执行的操作包括1、清除中断状态 2、抛出InterruptedException

    public static void main(String[] args) {
        Thread th = new Thread(){
            public void run(){
                try{
                    for(int i = 0; i<10; i++){
       //检测到中断后,会处理上面提到的2个操作
                        Thread.sleep(500);
                        System.out.println(i);
                        
                    }
                }catch(InterruptedException e){
                    e.printStackTrace();
//                  Thread.currentThread().interrupt();
                    System.out.println(Thread.currentThread().getName());
//此时返回false。若上面执行Thread.currentThread().interrupt();则返回true
                    System.out.println(Thread.currentThread().isInterrupted());
                }
            }
        };
        th.start();
        
        try{
            Thread.currentThread().sleep(1100);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        th.interrupt();
    }

你可能感兴趣的:(java中断)