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

What are the five steps to analyze thread and thread safety

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you what are the five steps of analyzing thread and thread safety, which are concise and easy to understand. I hope you can get something through the detailed introduction of this article.

What is a thread interrupt?

In fact, there is more than one thread of execution in our Java program, and the Java program ends only when all threads are finished. Officially, I'll give you a description: when all the non-daemon threads end, or when one of the threads calls the System.exit () method, the Java program ends.

Application scenario of thread interruption

Let's first give an example. For example, we are now downloading a blockbuster of more than 500m. We click to start the download. At that time, we start a thread to download our files. However, our network speed is not very powerful at this time. Dozens of KB are running here. As a young man, I can't wait. I won't come down. Well, at this time, our operation is to end the operation of downloading the file. in fact, closer to the program, we need to interrupt the thread at this time.

Let's next write the download code to see how to interrupt a thread. Here I have acquiesced that you have mastered how to create a thread. In this program, we simulate the download, get the system time at the beginning, and then enter the loop to get the system time each time. If the time exceeds 10 seconds, we interrupt the thread and stop downloading at 1m per second:

Public void run () {int number = 0; / record the start time of the program Long start = System.currentTimeMillis (); while (true) {/ / the end time of each execution Long end = System.currentTimeMillis (); / / get the time difference Long interval = end-start / / if the time exceeds 10 seconds, then we finish downloading if (interval > = 10000) {/ / interrupt thread interrupted (); System.err.println ("too slow, I won't get down"); return } else if (number > = 500) {System.out.println (File download complete); / / interrupt thread interrupted (); return;} number++; System.out.println ("downloaded" + number+ "M") Try {Thread.sleep (2000);} catch (InterruptedException e) {e.printStackTrace ();}}

The way a thread is interrupted

The Thread class provides us with a method to interrupt a thread, so let's take a look at how this method interrupts a thread:

Public static boolean interrupted () {return currentThread () .isInterrupted (true);}

This method checks whether the current thread is interrupted, returns true if interrupted, and returns false without interruption.

Private native boolean isInterrupted (boolean ClearInterrupted)

By looking at the source code, we can see that the interrupt thread sets the value to true by calling the method to check whether the thread has been interrupted. At this point, you will return true when you call the method to check whether the thread is interrupted.

Here we need to pay attention to a problem: the Thread.interrupted () method only modifies the state of the current thread to tell him that it has been interrupted, but for non-blocking threads, it only changes the interrupt state, that is, Thread.isInterrupted () returns true. For threads in cancelable blocking states, such as threads waiting on these functions, Thread.sleep (), the thread will throw an InterruptedException exception after receiving the interrupt signal. The interrupt state is also set to true.

The cause of abnormal InterruptedException caused by thread sleep

As a matter of fact, we all have little knowledge of this. I will write a wrong example. Let's take a look at it and figure out this problem thoroughly:

Public void run () {int number = 0; while (true) {/ / check whether the thread is interrupted, then stop downloading if (isInterrupted ()) {System.err.println ("too slow, I won't go down"); return } else if (number > = 500) {System.out.println (download complete); return;} number++; System.out.println (downloaded + number+ "M"); try {Thread.sleep (2000) } catch (InterruptedException e) {e.printStackTrace ();}

This is our main program. Wait 10 seconds before interrupting the thread.

Public static void main (String [] args) throws InterruptedException {Thread thread = new PrimeGenerator (); / / start thread thread.start (); / / interrupt thread Thread.sleep (1000) after waiting for 10 seconds; / / interrupt thread thread.interrupt ();}

It looks like a common program, but the truth is not what you see. In fact, this code will throw an InterruptedException exception. Let's analyze the reason.

First of all, we need to understand that the Thread.interrupt () method will not interrupt a running thread. When the Thread.sleep () method is called, it will no longer occupy CPU. Let's analyze our program. We have to wait 10 seconds for downloading, and the speed of each download is 0.5M/S, that is, when we download to 5m, the waiting time has already expired, and call the Thread.interrupt () method to interrupt the thread. But the sleep in the run () method continues to execute, and it will not give up execution of the following code because of the interrupt, so when it executes Thread.sleep () again, it will throw an InterruptedException exception because the current thread has been interrupted.

Speaking of which, do you understand the cause of this anomaly? There are two other reasons why a thread produces an InterruptedException exception, and the improper use of the wait () and join () methods will also cause the thread to throw the exception.

Two ways to see if a thread is interrupted

In the Thread class, there is a method interrupted () that can be used to check that the current thread is interrupted, and the isInterrupted () method can be used to check whether the current thread is interrupted.

The underlying way to interrupt a thread is to set this property to the true,isInterrupted () method and just return the value of the property.

One difference between the two methods is that isInterrupted () cannot change the property value of interrupted (), but the interrupted () method can change the property value of interrupted, so we recommend using isInterrupted () when judging that a thread is interrupted.

The above is to analyze what are the five steps of thread and thread safety. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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

Development

Wechat

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

12
Report