How to gracefully stop the thread?

A long time ago, in a village called "Springboot", there lived a group of programmers who loved programming. They like to explore new technologies, optimize their code, and work hard to build better software.

In this village, there is a programmer named Xiao Ming, who is one of the best programmers in the village. He likes to use Springboot to develop applications very much, and in the process of using Springboot, he encountered a problem: how to stop threads gracefully.

Xiaoming knows that threads are very important because they are responsible for handling various tasks of the application. If the thread is not properly stopped, it will cause the application to crash and possibly even corrupt the data. Therefore, stopping threads must be done very carefully.

Xiao Ming began to study how to stop threads gracefully, and finally found a very good solution. He shared this solution with other programmers, hoping that they can also benefit from it.

So, how did Xiao Ming stop the thread gracefully?

use flags

In the application, we can define a flag to indicate whether the thread needs to be stopped. For example, in a loop, we can decide whether to continue execution by judging the value of the flag bit. When the thread needs to be stopped, we only need to set the flag bit to true.

Sample code:

typescriptCopy codepublic class MyThread implements Runnable {
    private volatile boolean stopFlag = false;
    
    @Override
    public void run() {
        while (!stopFlag) {
            // do something
        }
    }
    
    public void stop() {
        stopFlag = true;
    }
}

In the application, we can stop the thread by calling the stop method of MyThread. When stopping the thread, we can wait for a period of time to let the thread exit naturally, or interrupt the thread through the Thread.interrupt method.

Use ExecutorService

In Spring Boot, we can use ExecutorService to manage the thread pool. When the thread needs to be stopped, we can call the shutdown method of ExecutorService to stop the thread pool. When all threads are executed, the thread pool will be automatically closed.

Sample code:

javaCopy code@Service
public class MyService {
    @Autowired
    private ExecutorService executorService;
    
    public void execute() {
        executorService.execute(new MyTask());
    }
    
    public void shutdown() throws InterruptedException {
        executorService.shutdown();
        executorService.awaitTermination(60, TimeUnit.SECONDS);
    }
    
    private class MyTask implements Runnable {
        @Override
        public void run() {
            // do something
        }
    }
}

In the application, we can stop the thread pool by calling the shutdown method of MyService. When stopping the thread pool, we can wait for a period of time to let the thread exit naturally, or interrupt the thread pool through the ExecutorService.shutdownNow method.

Shutdown Hook using Spring Boot

In Spring Boot, we can use Shutdown Hook to stop the thread when the application is closed. When the application shuts down, Spring Boot calls all registered Shutdown Hooks to perform cleanup operations.

Sample code:

javaCopy code@Component
public class MyShutdownHook implements Runnable {
    @Autowired
  private MyThread myThread;

@Override
public void run() {
    myThread.stop();
}

public void setMyThread(MyThread myThread) {
    this.myThread = myThread;
}
}

At application startup, we can register MyShutdownHook with Spring Boot:

@SpringBootApplication
public class MyApp {
	@Autowired
	private MyThread myThread;
  @Autowired
	private MyShutdownHook myShutdownHook;

public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
}

@Bean
public CommandLineRunner commandLineRunner() {
    return args -> {
        // 启动MyThread线程
        Thread thread = new Thread(myThread);
        thread.start();
        
        // 注册MyShutdownHook
        Runtime.getRuntime().addShutdownHook(new Thread(myShutdownHook));
        myShutdownHook.setMyThread(myThread);
    };
}
}

When the application is closed, Spring Boot will call the run method of MyShutdownHook to stop the thread.

Through these measures, Xiao Ming successfully stopped the thread gracefully and avoided unnecessary losses. Other programmers started to adopt this approach, and their applications became more robust and reliable.

In this story, Xiao Ming told us that it is very important to stop the thread, and it is necessary to stop the thread gracefully. If you are also using Springboot to develop applications and encounter the problem of stopping threads, then you can refer to Xiaoming's approach. I believe these methods can help you manage your threads better and make your application more robust and reliable.

 

Guess you like

Origin blog.csdn.net/Dark_orange/article/details/130493080