How to stop the thread correctly?

 In Java, the correct way to stop a thread is usually to use a cooperative approach, rather than forcefully terminating the thread. Forcibly terminating threads can lead to issues such as resource leaks or data inconsistencies. Here is a code example that demonstrates how to properly stop a thread:

public class MyThread implements Runnable {
    private volatile boolean running = true;

    public void stopThread() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            // 线程的业务逻辑
        }
    }
}

  In the above code, the MyThread class implements the Runnable interface and contains a running flag to control whether the thread continues to execute. When the stopThread method is called, it will set the running flag to false, thus terminating the thread.

  Next, let's look at an example using the above thread class:

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.start();

        // 停止线程的逻辑
        try {
            Thread.sleep(1000); // 假设等待1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        myThread.stopThread(); // 停止线程

        // 等待线程结束
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("线程已停止");
    }
}

  In the above example, we created a MyThread instance and passed it to the Thread constructor to create a new thread. Then, we call the myThread.stopThread() method to stop the thread. To ensure that the thread has stopped, we use the thread.join() method to wait for the thread to end.

  Note that the running flag is declared volatile, this is to ensure visibility between threads. Doing this ensures that threads see the latest value when checking the running flag.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130965457