当前位置:网站首页>Multithread interrupt usage

Multithread interrupt usage

2022-06-22 03:52:00 Max constant

Two knowledge points involved in this paper

  1. interrupt() : Interrupt thread

If the interrupted thread is sleep,wait,join Can cause interruption The thread threw InterruptedException, And get rid of Interrupt mark remember
; If you interrupt a running thread , Will set up Interrupt mark remember ;park Thread interrupted , It will also set up Break mark

  1. isInterrupted(): Determine whether the current thread is interrupted

Will clear Break mark

Sample code

public class interrupt usage  {
    

    public static void main(String[] args) throws InterruptedException {
    
        Thread t1 = new Thread(() -> {
    
            while (true) {
    
                boolean interrupted = Thread.currentThread().isInterrupted();
                if (interrupted){
    
                    System.out.println(" Interrupted ,  Exit loop ");
                    break;
                }else {
    
                    System.out.println(" Normal execution is not interrupted --");
                }
            }
        }, "t1");

        t1.start();
        Thread.sleep(100);

        System.out.println(" Start interrupt");
        t1.interrupt();

    }
}

 Insert picture description here
When the thread sleep is completed Thread.sleep(100), Here we go interrupt Interrupt thread , The method is then executed in the loop isInterrupted(), The return result is true, It means that the thread has been interrupted

原网站

版权声明
本文为[Max constant]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220322580673.html