This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

How do I properly interrupt a thread?

Methods provided by threads

  • interrupt

By calling this method, the system marks the current thread with an interrupt flag (true). The default is false. If another thread calls this method in the current thread, it tells the current thread that you can stop, and the current thread can continue regardless

  • isInterrupted

Determine whether the current thread is interrupted, according to the current thread interrupt flag, do relevant processing

  • Thread.interrupted() checks whether a Thread has been interrupted. This method is static and, unlike isInterrupted, resets the interrupt flag to false after checking
1.1 Interrupt operations using methods provided by Thread (Recommended)
 final Thread thread=new Thread("TestCustomisInterrupted") {@Override
            public void run(a) {
                super.run();
                // The default flag bit is false
                while(! isInterrupted()){ System.out.println(currentThread().getName()+"::::runing.......");
                }
                System.out.println("Execution completed ::::"+isInterrupted());  //true}}; thread.start();try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
Copy the code

Here is a simple example of what happens if the current thread has a blocking method in its execution body:

 final Thread thread=new Thread("TestCustomisInterrupted") {@Override
            public void run(a) {
                super.run();
                // The default flag bit is false
                while(! isInterrupted()){try {
                        sleep(1000);
                        System.out.println(currentThread().getName()+"::::runing.......");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Execution completed ::::"+isInterrupted());  //true}}; thread.start();try {
            Thread.sleep(2000);
        } catch(InterruptedException e) { e.printStackTrace(); } thread.interrupt(); Input the result TestCustomisInterrupted: : : : running... java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.example.socket.MyClass$1.run(MyClass.java:78)
TestCustomisInterrupted::::runing.......
TestCustomisInterrupted::::runing.......
TestCustomisInterrupted::::runing.......
Copy the code

It’s going to raise an interrupt exception and reset the interrupt flag to false, the thread is not going to stop and it’s going to keep executing, and if you want to keep executing the interrupt you can keep setting the interrupt in the exception

Using the thread.interrupted () static method, if interrupted occurs, the interrupt flag is set to Fasle

  final Thread thread=new Thread("TestCustomisInterrupted") {@Override
            public void run(a) {
                super.run();
                // The default flag bit is false
                while(! Thread.interrupted()){ System.out.println(currentThread().getName()+"::::runing.......");
                }
                System.out.println("Execution completed ::::"+isInterrupted());  //true}}; thread.start();try {
            Thread.sleep(2000);
        } catch(InterruptedException e) { e.printStackTrace(); } thread.interrupt(); TestCustomisInterrupted::::runing....... TestCustomisInterrupted::::runing....... Execution completed ::::false
Copy the code

2. Terminate a thread through a thread custom field

 class MyRunable implements Runnable{
            boolean isRun=true;

            public boolean isRun(a) {
                return isRun;
            }

            public void setRun(boolean run) {
                isRun = run;
            }

            @Override
            public void run(a) {
                while (isRun){
                    System.out.println("::::runing.......");
                }
                System.out.println("Execution completed ::::"+isRun);  //true
            }
        }
        MyRunable myRunable=new MyRunable();
       new Thread(myRunable).start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myRunable.setRun(false); ::::runing....... ::::runing....... ::::runing....... ::::runing....... ::::runing....... Execution completed ::::false
Copy the code

Threads can also be stopped using custom tags, so how is that different from the methods provided by threads? When we have a blocking method in our run method logic

        class Mythread extends Thread{
            boolean isRun=true;

            public boolean isRun(a) {
                return isRun;
            }

            public void setRun(boolean run) {
                isRun = run;
            }
            @Override
            public void run(a) {
                super.run();
                while (isRun()){
                    try {
                        Thread.sleep(4000);
                        System.out.println("::::runing.......");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Execution completed ::::"+isRun());  //true
            }
        }

        Mythread mythread=new Mythread();
        mythread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mythread.setRun(false);

Copy the code

Mythread.setrun (false); myThread.setrun (false); The thread does not stop immediately. It does not stop until after the run method has been executed

3. Use the stop, suspend, and resume methods of threads

The above three methods are provided by thread, but they are now marked expired, so they are not recommended. The reason is that stopping the thread system will not release the resources occupied by the thread, because it does not give the thread the opportunity and time to release the resources, which will cause other problems, so it is not recommended to use them.