Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to stop a thread using interrupt

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use interrupt to stop threads". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

It's easy to start a thread by calling the start () method of the Thread class and defining the tasks that need to be executed in the run () method, but you need to pay attention to stopping a thread correctly.

One: how to stop the thread correctly

Typically, instead of manually stopping a thread, we allow the thread to run to the end and then let it stop naturally. However, there will still be many special situations that require us to stop the thread in advance, such as the user shuts down the program suddenly, or the program restarts when running an error. In particular, threads that are about to stop are still valuable in business scenarios, so we need to stop threads correctly. However, Java does not directly provide the ability to simply and safely stop threads.

1.1 Thread stop Design principles

Java hopes that programs can notify each other and cooperate with each other to manage threads, because if you don't know what each other is doing, rashly forcing threads to stop may cause some security problems. In order to avoid problems, you need to give each other a certain amount of time to sort out the final work.

For example, when a thread is writing a file and receives a termination signal, it needs to choose whether to stop immediately or after writing the entire file successfully, according to its own business judgment. If you choose to stop immediately, the data may be incomplete. Neither the initiator of the interrupt command nor the receiver wants the data to have a problem.

So the most correct way for Java to stop a thread is to use interrupt. Because the interrupt only serves to notify the stopped thread. For the stopped thread, it has full autonomy, it can choose to stop immediately, can choose to stop after a period of time, or can choose not to stop at all.

1.2 how to use interrupt to stop a thread while (! Thread.currentThread () .isInterrupted () & & has more work to do) {do more work}

After calling the interrupt () method that uses a thread, the interrupt marker bit of that thread is set to true. Every thread has such a tag bit, which should be checked periodically when the thread executes. If the flag bit is set to true, it means that a program wants to terminate the thread. As you can see in the pseudocode above, in the while loop body judgment statement, we first determine whether the thread is interrupted by Thread.currentThread (). IsInterrupt (), and then check to see if there is any work to be done.

Use interrupt to stop the thread correctly:

Public class StopThread implements Runnable {@ Override public void run () {int count = 0 / / exit loop indicates that the interrupt flag bit is set to true (someone wants to stop the thread) or task completion while (! Thread.currentThread (). IsInterrupted () & & count < 1000) {/ / interrupt is marked as false (unchanged), and if there is a task to do, enter the loop. Judge System.out.println ("count =" + count++) each time. }} public static void main (String [] args) throws InterruptedException {Thread thread = new Thread (new StopThread ()); thread.start (); / / Sleep Thread.sleep (5); thread.interrupt ();}}

The child thread will be started in the main function, and then the main thread will immediately send an interrupt signal to the child thread after sleeping for 5 milliseconds. The child thread will detect the interrupt signal and stop before it has finished printing 1000 numbers. This is the case where the thread is stopped correctly through interrupt.

1.2.1 can threads feel interrupt interruptions during Sleep

Java designers took this into account at the beginning of their design. Sleep, wait and other methods that can let the thread into blocking make the thread sleep, and the dormant thread is interrupted, then the thread can feel the interrupt signal, and will throw an InterruptedException exception, at the same time clear the interrupt signal and set the interrupt flag bit to false. In this way, you don't have to worry that the thread will not feel the interrupt during a long sleep, because even if the thread is still dormant, it can still respond to the interrupt notification and throw an exception.

Public class StopDuringSleep implements Runnable {@ Override public void run () {int num = 0; while (! Thread.currentThread (). IsInterrupted () & & num

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report