Steal a skill from the gold diggers. In order to improve knowledge extraction and literal expression, try to express the essence of technical knowledge in words with the length of the post code. (Simply, “Speak more.”)

Start the text!

Antecedents feed

There is no official definition of the term “inter-thread communication”, perhaps it is a colloquial term. The following is a definition based on my personal understanding, with emphasis on rigor.

Different threads affect each other’s execution logic through resource state synchronization.

Basic communication between threads can be divided into starting and ending, thread waiting and thread waking. In JAVA, they all correspond to fixed API and fixed usage, but there are other ways of communication, but this article will not expand.

One, the character difference of thread stop

The story of Zhang SAN and Xiao Ming

1. thread.stop()Stupid and rude Zhang SAN

Immediately force the execution of a thread to stop, interrupt code execution instructions, and exit the thread. Threads that have been stopped cannot safely be cleaned up.

For example, stupid Zhang SAN arranges his son Xiao Ming to boil water. Xiao Ming is very clever, has remembered the steps of boiling water, take the pot water, fire, water boiling off the fire.

Xiao Ming is very obedient, they entered the kitchen began to busy.

Half a minute later, Stupid Zhang SAN’s phone suddenly rang, and the relevant department informed him that the gas supply would be stopped immediately. Zhang SAN realized that Xiao Ming could not boil water any more, so he decided to stop Xiao Ming’s work.

At this time xiaoming is still in the water, but the stupid Zhang SAN pretended not to see, he pulled Xiaoming out of the kitchen. Xiao Ming’s heart is very confused, but he has a bitter can not say.

After they left, the water in the kitchen was still pouring, and finally flooded the kitchen…

Conclusion: You don’t need to worry about the thread to stop() at all

2. thread.interrupt()Gentle Zhang SAN

Notify a thread to interrupt a task that is currently executing. The thread that has been interrupted can either exit the thread internally or not.

I’m going to plug in the characters, and I’m going to go back to the chestnuts. This but this time after zhang SAN did not directly take Xiaoming, but loudly told Xiaoming, it is time to leave the kitchen.

Xiao Ming has two choices at this time, the first is to drop what is in hand, immediately out of the kitchen, let the water continue splashing. The second is to turn off the tap and leave the kitchen.

If you were Xiao Ming, what would you do?

Bottom line: To interrupt a thread, use thread.interrupt(), or at least gently

3.Thread.interrupted()Poor Xiao Ming, the correct answer can only be obtained once

Return true on the first call after an interrupt, and false until no interrupt is made

I’m going to plug in the characters, and I’m going to go back to the chestnuts. Xiao Ming knew that Zhang SAN might inform him of the exception, so Xiao Ming checked whether to stop before every key step, and if he found that he was stopped, he would immediately deal with the aftermath and leave the kitchen. Because he knows he’s basically only got one shot.

Bottom line: Use it for simple tasks. If you can’t measure simplicity, don’t use it unless you’re very sensitive to the number of interrupts.

4.isInterrupted()Happy Xiao Ming, get the correct answer as many times as possible

As long as it is interrupted once, all subsequent states are true

Do you understand xiao Ming’s happiness

Conclusion: Do you understand xiao Ming’s happiness

5.Thread.sleep(x)Xiao Ming fell asleep in the kitchen

The current thread enters the suspended state. The suspended thread may be interrupted. If the suspended thread is caught by Catch (InterruptedException E), the thread can clean up the situation and choose whether to exit.

Into the role, that’s right xiaoming really fell asleep! If the gentle Zhang SAN loudly told Xiaoming to leave the kitchen, xiaoming woke up after the orderly stop when and stage work if not confused, such as turn off the faucet, and then leave the kitchen.

What if Ming gets confused? Xiao Ming usually doesn’t get confused

Because he knew

Make confused xiaoming will be beaten by Zhang SAN!

Summary: The catch (InterruptedException e) that needs to be caught after thread.sleep (x) is better understood as an exception because it does not represent a program error

Second, the difference between the details of waiting and waking up

The story of Xiao Ming and Xiao Fang

1.wait()The quality of Xiao Ming

If the resources to be accessed do not meet the requirements, enter the waiting area. The lock is contested until it is awakened, and the logic continues after the lock is acquired

Xiao Ming and Xiao Fang together to watch TV, Xiao Ming first grabbed the remote control, he wanted to watch the football game, cut to the football channel, player A ready to shoot, but Xiao Ming’s beer hasn’t arrived, Xiao Ming watch the game must have beer.

If Ming is rude, then he pauses the TV, sits the remote under his butt, and keeps staring at the TV until the beer arrives and Ming restores the TV and continues to watch.

If Ming is polite, he will give up the remote control first, and Xiao Fang takes it and plays the legend of Zhen Huan happily. Xiao Ming was in A dazed state (detail 1) until someone told him that the beer was coming (detail 2), so he grabbed the remote control again (detail 3). After grabbing the back remote control, he went to the football channel. The TV picture started directly from the point where player A was preparing to shoot (detail 3).

What if xiao Ming had an accident when he was in a daze? There is no need to worry that this will wake xiao Ming up immediately. He can choose what to do next.

This is why catch (InterruptedException e) is also required when wait()

Summary: Use wait() to release locks and resources to reduce the wait time of sibling threads

2.notify()The lucky goddess

One of the threads associated with the current lock that entered wait() is randomly awakened by the object currently acting as the lock, and the awakened thread re-races the lock

From god’s point of view, when a resource can only be used by one thread, use notify() to save unnecessary overhead.

The selected thread is the only lucky one

3.notifyAll()The sun shines

All threads associated with the current lock that are in wait() are awakened by the object currently acting as the lock. The awakened threads re compete for the lock

If there are no special considerations, you should normally wake up all threads that are in waiting for world peace.

3, Join quickly to bind a bound timing

To connect multiple parallel threaded tasks into a single serial threaded task. Whether the lead thread succeeds or fails, the following thread executes immediately

Another example of chestnuts, Zhang SAN arranged xiao Fang cooking, and let Xiao Ming responsible for playing soy sauce.

This is where it gets really interesting.

Xiao Fang needs soy sauce when she finishes cooking, but Xiao Ming hasn’t bought back soy sauce yet. Xiao Fang will use the join method to bind himself to the end of the task of Xiao Ming to buy back soy sauce timing.

The result? If Xiao Ming bought back soy sauce, xiao Fang use soy sauce fresh after loading out of the pot.

If Xiaoming fell on the way, resulting in an early exit from the mission. Xiao Fang is the use of empty soy sauce after the plate out of the pot

This is not to blame xiao Fang, she did not know xiao Ming did not bring back soy sauce.

Conclusion: After join(), we should judge whether the condition is met here to avoid getting NPE

Four, yield

Give a little time slice to the same level thread, and immediately resume their own execution.

Something like a quick wait() (not the one called) and then a quick auto-recovery

Lack of scientific analysis and verification, dare not say more ~


END