Java basic sleep and interrupt

 2 minutes to read

Java basic sleep and interrupt

  1. interrupt is used to send a termination notification signal to the thread, which will affect the interrupt flag bit inside the thread

  2. The current thread itself will not change its state due to interruption. The specific change of the state needs to be determined by waiting for the final processing result of the program that receives the interrupt representation.

  3. Calling interrupt will not interrupt the running of the current thread, it only changes the interrupt flag bit.

  4. If the thread is blocked due to calling the sleep method, then calling the interrupt method will throw an InterruptedException and the thread will end early.

  5. The interrupt flag will be cleared before throwing an exception, and calling isInterrupted() after throwing an exception will return false.

  6. The thread can be safely terminated by the interrupt flag bit

Terminate thread safely
  1. First call the interrupt method to change the interrupt flag bit

  2. Use isInterrupted() in the run method to judge

code show as below:

public class SleepInterrupt {
    public static void main(String[] args) {
        Runner2 r = new Runner2();
        r.start();
        try
        {
            Thread.sleep(4000);
        }catch(InterruptedException e) {
        }
        r.interrupt();
    }


    static class Runner2 extends Thread{
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("---this is run---");

                try {
                    Thread.sleep(1000);
                }catch(InterruptedException e) {
                    System.out.println("---catch interrupt---");
                    this.interrupt();
                }
            }
            System.out.println("---end---");
        }
    }

}

Calling isInterrupted() after throwing an exception will return false, so to terminate the thread, call this.interrupt(); The interrupt flag becomes true, and the thread does not meet the running conditions to end running.