How to control the start and stop of multiple threads in Java?

In Java, there are several common ways to control the start and stop of multiple threads.

  1. Using the Thread class: You can start a thread by calling the start() method of the Thread class and stop a thread by calling the interrupt() method of the thread object.
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        // 线程执行的代码
    }
});
thread.start(); // 启动线程
thread.interrupt(); // 停止线程
  1. By using the Runnable interface, you can start a thread by creating an object of a class that implements the Runnable interface and then passing it to the constructor of the Thread class. The method to stop the thread is the same as mentioned above.
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // 线程执行的代码
    }
};

Thread thread = new Thread(runnable);
thread.start(); // 启动线程
thread.interrupt(); // 停止线程
  1. Utilize shared variables: Shared variables can be used to control the start and stop of threads. By setting the value of a shared variable, you can control the execution logic of threads, allowing them to exit a loop under certain conditions and consequently stop the thread.
volatile boolean isRunning = true; // 共享变量

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        while (isRunning) {
            // 线程执行的代码
        }
    }
});

thread.start(); // 启动线程
isRunning = false; // 停止线程

It is important to note that the methods mentioned above control the start and stop of threads through cooperation, meaning the thread itself decides when to exit. Additionally, the method of stopping a thread is not by forcefully terminating it, but rather by setting a flag or sending an interrupt signal to request the thread to stop. The thread checks these conditions at appropriate times and voluntarily exits the loop, thus halting the execution of the thread.

bannerAds