Interrupt related methods in Java threads will be seen at a glance

For these series of methods, we must first clearly know the transition of the thread running state to better understand.

A thread declaration cycle: initial, ready, running, blocking, running, dead.


                                                                                                                                        (The picture is found on the Internet, invaded and deleted!!!)

There are three reasons for blocking: waiting blocking, synchronization blocking, other blocking (sleep, join, IO blocking)

In the Java method, waiting is wait, synchronization is syn block, sleep is sleep, and join blocking is generated by join.

Generally we will say that interrupt is the interrupt flag, then we will say in detail:

    A thread should not be interrupted or stopped by other threads, but should be interrupted by itself.

    Therefore, Thread.stop, Thread.suspend, and Thread.resume have all been abandoned.

And Thread.interrupt does not interrupt the thread, it just informs the thread that "you should be interrupted".


So next, let's take a look at the similar naming method


Looking at the api shows that there are three similar methods.

  


Two differences:

1. interrupted is a static method that acts on the current thread, and isInterrupted acts on the thread corresponding to the thread object that calls the method.

( The thread corresponding to the thread object is not necessarily the currently running thread )

2. These two methods are the same method, but the parameters are different. Looking at the comments above, you can understand that the former has the function of clear marking.

      In general, a thread can be stopped normally through the cooperation of the interrupt and interrupted methods. Thread A informs thread B to let it end the thread through the interrupt method of thread B. Inside the run of thread B, the loop detects whether interrupted is really coming. Accept the signal from thread A, throw an exception if true, do the cleanup in the catch, and end the thread.

       If the thread is in a non-blocking state when it is interrupted, the interrupt flag is modified to true, and on this basis, once it enters the blocking state, it is processed according to the blocking state ; for example, a thread is in the running state, The interrupt flag is set to true, after that, once the thread calls one of the wait, jion, and sleep methods, an InterruptedException is thrown immediately, and the interrupt flag is cleared and reset to false. Programmers use try-catch to catch exceptions thrown by JVM to do various processing and how to exit the thread.

Let's look at a few examples:

public class Test {

    public static void main(String[] args) {
        Thread t = new Thread(new worker());

        t.start();
        try{
            Thread.sleep(200);   
            //System.out.println(Thread.currentThread().isInterrupted()); Indicates the current main thread
            //System.out.println(t.isInterrupted()); work child thread
        }catch (InterruptedException e){
            System.out.println("main is exception");
        }

        t.interrupt();
        System.out.println("Main Thread is stopped");
    }
}

class worker extends Thread{
    @Override
    public void run() {
        super.run();
        //System.out.println(Thread.currentThread().isInterrupted()); // Represents the current work thread
        System.out.println("work is start");
        try{
            Thread.sleep(500);
        }catch (InterruptedException e){
            System.out.println("work isInterrupted()" +
                    Thread.currentThread().isInterrupted());
        }
        System.out.println("work is stop");
    }
}


The main thread starts a sub-thread, and the worker thread sleeps for 500ms, while the main sleeps for 200ms. After that, the main     calls the interrupt method of the work to interrupt the work (notifying the work that you should end it yourself), and the work is interrupted. Exception, work throws an exception , and the interrupt flag is cleared.


public class Test1 {
    public static void main(String[] args) {
        try{
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(200);
            thread.interrupt();
        }catch (InterruptedException e){
            System.out.println("main catch");
        }
            System.out.println("end");
    }
}
class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
            Thread.sleep(200000);
            System.out.println("run end");
        }catch (InterruptedException e){
            System.out.println("Stop in sleep" + this.isInterrupted());
            e.printStackTrace ();
        }
    }
}

Swap the interrupt and sleep in the main thread, clear the execution order, and pay attention to the difference between the order of sleep and interrupt.

Method to stop thread - exception method

public class Test {
    public static void main(String[] args) {
        try{
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(10); // Don't set the time too long, otherwise the interrupt is marked after running directly
            thread.interrupt();
        }catch (InterruptedException e){
            System.out.println("main catch");
        }
            System.out.println("end");
    }
}
class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
           for(int i = 0; i < 50000; i ++){
               if(Thread.interrupted()){
                   System.out.println("stopped");
                   throw new InterruptedException();
               }
               System.out.println("i= " + (i + 1));
           }
            System.out.println("Test output"); // The output does not come because an exception was thrown directly and the catch arrives
        }catch (InterruptedException e){
            System.out.println("Entered the catch");
            e.printStackTrace ();
        }
    }
}

Summarize:

The interrupt sets the flag bit . In the non-blocking state, it will be changed to true. Once it enters the blocking state, an exception will be thrown and the interrupt flag will be cleared.

interrupted is a static method that returns the interrupted status of the current thread. The first call returns true, then clears the flag, and the second time is false. Of course, no interrupt exception is thrown during this period, otherwise the interrupt exception will be cleared.

isInterrupted will always return true unless the interrupt status is cleared.



Supplement: Can threads in java catch interrupt exceptions and handle them when they are blocked? (not running on cpu)


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935564&siteId=291194637