How to properly interrupt a thread?

This article has participated in the "Newcomer Creation Ceremony" activity, and started the road of Nuggets creation together

How to properly interrupt a thread?

1. Methods provided by threads

  • interrupt

By calling this method, the system will mark the current thread with an interrupt flag (true), the default is false, if other threads call this method in the current thread, it means that you can stop the current thread, and the current thread can also ignore it continue

  • isInterrupted

Determine whether the current thread is interrupted, and do related processing according to the current thread interrupt flag bit

  • Thread.interrupted() determines whether the thread is interrupted. This method is a static method. Unlike isInterrupted, the interrupt flag bit will be reset to false after the judgment.
1.1 Interrupt the operation through the method provided by Thread (recommended)
 final Thread thread=new Thread("TestCustomisInterrupted"){
            @Override
            public void run() {
                super.run();
                //默认标志位 为false
                while (!isInterrupted()){
                    System.out.println(currentThread().getName()+"::::runing.......");
                }
                System.out.println("执行完成::::"+isInterrupted());  //true
            }
        };

        thread.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
复制代码

The above is a relatively simple example, what if there is a blocking method in the current thread execution body:

 final Thread thread=new Thread("TestCustomisInterrupted"){
            @Override
            public void run() {
                super.run();
                //默认标志位 为false
                while (!isInterrupted()){
                    try {
                        sleep(1000);
                        System.out.println(currentThread().getName()+"::::runing.......");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("执行完成::::"+isInterrupted());  //true
            }
        };

        thread.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();

输入结果

TestCustomisInterrupted::::runing.......
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.......
复制代码

An interrupt exception will be thrown, and the interrupt flag will be reset to false. The thread will not stop and will continue to execute. If you want the program to continue to perform the interrupt operation, you can continue to set the interrupt operation in the exception.

Using the Thread.interrupted() static method to judge, if an interrupt occurs, the interrupt flag bit will be directly set to fasle

  final Thread thread=new Thread("TestCustomisInterrupted"){
            @Override
            public void run() {
                super.run();
                //默认标志位 为false
                while (!Thread.interrupted()){
                        System.out.println(currentThread().getName()+"::::runing.......");
                }
                System.out.println("执行完成::::"+isInterrupted());  //true
            }
        };

        thread.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();

TestCustomisInterrupted::::runing.......
TestCustomisInterrupted::::runing.......
执行完成::::false
复制代码

2. Terminate the thread through the thread custom field

 class MyRunable implements Runnable{
            boolean isRun=true;

            public boolean isRun() {
                return isRun;
            }

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

            @Override
            public void run() {
                while (isRun){
                    System.out.println("::::runing.......");
                }
                System.out.println("执行完成::::"+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.......
执行完成::::false
复制代码

You can also use a custom tag to stop a thread. How is it different from the method provided by the thread? When there is a blocking method in our run method logic

        class Mythread extends Thread{
            boolean isRun=true;

            public boolean isRun() {
                return isRun;
            }

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

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

复制代码

After adding the sleep method, it is found that the thread called when the thread sleeps mythread.setRun(false);will not stop immediately, and will not stop until the sleep time reaches the execution of the run method.

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

The above three methods are provided by thread, but they are now marked expired and are not recommended to be used, because using the above methods, stopping the thread system will not release the resources occupied by the thread, because there is no opportunity and time for the thread to release resources, which will cause other issues, so it is not recommended.

Guess you like

Origin juejin.im/post/7079289870526447646