Mp.weixin.qq.com/s/UkUEMmXm9…

In order to explain the concept of locking objects, I recently came up with a graphic story while giving a lecture on concurrent programming in Java.

Later, I realized that this story seemed to explain many core concepts in Java concurrent programming, so I refined it into this article.

The story may be strange. There is such a school, there are a lot of people, we are simply divided into students, teachers, and dormitory administrator aunt.

There is also a wonderful fruit supermarket in the middle of the school, where there is a warehouse with apples, watermelons and oranges. People who come to this supermarket, on the one hand, can take the fruit and eat it, on the other hand, they can bring the fruit and pay back the money.

Students can only eat or give apples, teachers can only have watermelons and the dorm lady can only give oranges.

The entrance and exit of the supermarket is also very well regulated. People who come to the supermarket must hold corresponding certificates, students need to hold student ID cards, teachers need to hold teacher id cards, dormitory administrator aunt need to hold aunt card.

There is only one certificate for each of these three certificates, which are kept in a claim office at the entrance of the supermarket. Before entering the supermarket, people must go to the evidence office to get the corresponding certificate before entering.

If the card is temporarily taken away by others can not get, you need to queue up in the waiting area behind the card.

There are also three waiting areas, namely student ID waiting area, teacher id waiting area and aunt ID waiting area.

Entering the supermarket is even more bizarre, whether to take fruit from the supermarket, or to deliver fruit, all need to be controlled by a console, and this console, can only be operated by one person at a time.

In order to prevent someone from occupying the console for too long, only one person is allowed to operate the console for 10 seconds. After 10 seconds, an ID will be displayed on the screen, and only the person with this ID can operate the console

As for the choice of what number, teachers and students or dormitory administrator aunt can not decide and intervention, can only let the console to decide.

Fortunately, everyone has their own account on the console, and data that is half interrupted is not lost.

That’s the background of the story, and then all sorts of things happen at the school.

Let’s assume, first of all, that the people who come to this school are going to do things at the supermarket. At one point, a number 2 appeared on the desk, which was announced to everyone on various school screens.

So ID is 2 student Xiaoming saw his number, learned that he obtained the right to enter the supermarket operation console, then set out for the supermarket.

Xiao Ming first went to the door of the supermarket and asked the management of the identification office, “Give me a student CARD!” .

The administrator looked for a student ID card and gave it to Xiao Ming. Xiao Ming got his student ID card, entered the supermarket smoothly, sat on the operation desk, and logged in his account system.

The purpose of Xiao Ming’s visit is to take an apple, so he clicks the apple product icon, the system shows that there are four apples. So Ming successfully took away the apples, and the system recorded the number of apples -1 and the new number of apples 3 in the total system library.

Then Xiao Ming walked out of the supermarket, returned his student ID card to the identification office, walked out of the campus, and disappeared in the crowd outside.

Then no. 3 was displayed on the console, again via the school’s big screen. Xiao Zhang, a student with ID no. 3, saw his number and learned that he had gained access to the supermarket’s operation console, so he set off for the supermarket.

Xiao Zhang and Xiao Ming did exactly the same thing, but Xiao Zhang was too slow. As soon as he finished clicking on the apple product icon, the system showed the next person’s number 5. At this point Xiao Ming can only be forced to terminate their operation, give up the right to work.

Xiao Wang, a student with ID no. 5, went to the supermarket excitedly after receiving the notice and asked the management staff at the identification office, “Give me a student ID card!”

The management staff searched and found that the student ID card had been taken away by Xiao Zhang. They could only tell Xiao Wang, “Sorry, the student ID card is not available at the moment, please queue up in the waiting area behind the student ID card!” . Xiao Wang had no choice but to queue up obediently.

At this time, the console showed no. 3 again, which was just in the middle of the operation. Zhang was still in the supermarket and did not need to re-enter, so Zhang hurried to the operation desk to continue the operation, took an apple, left the supermarket, and returned the student ID card.

At this time, the management staff of the id office received the student ID card and shouted to the student ID queue area behind, “There is a student ID card, people in line come and get it!”

When Wang no. 5, who was waiting in line, heard this, he came out of the queue and prepared to get the certificate and enter the supermarket. But at this time, the number displayed on the operating table is another student No. 10. Student No. 10 took away his student ID card, entered the supermarket and began to operate.

Operation to half, the time limit of the operating platform has come up again, showing Xiao Wang’s ID number 5. Wang just got out of the queue and finally got permission to proceed to the next step. He went to the card office and said, “Give me a student CARD!”

As the student ID card had been taken away by 10th, the administrator could only say, “Sorry, the student ID card is not available at the moment, please queue up in the waiting area of the student ID card at the back!” .

When Xiao Wang saw that he had waited so long, he was beaten by others. He just wanted to say dirty words and thought of the famous saying of the school, “The world is not fair”, so he obediently went to the waiting area for the student ID card and continued to line up.

And so on no. 10 out of the operation, but also the student card, Xiao Wang was received by the card office manager shout, “student card has, line up people come to take it!” .

Wang walked out of the line, and the console finally showed wang’s number 5. This time, Xiao Wang successfully got his student ID card, entered the supermarket, sat on the operating table and logged in his own system.

Wang wanted to buy apples, so he clicked the button of Apple products, but the system showed that the number of apples was 0! Xiao Wang thought about it and had a plan:

  1. Stay in the supermarket and check the number of apples at the counter whenever possible until there are apples.

    But by staying in the supermarket, students who wanted to bring apples to the supermarket might not get their student ID cards, and they would never get apples.

  2. So Wang’s other idea is to go out of the supermarket, hand in his student ID card, and wait for the next opportunity to enter the supermarket to check the number of apples until there are apples.

    There was a chance of getting apples, but it was exhausting, and every trip was wasted if no one had delivered them to the supermarket at all.

  3. So Xiao Wang came up with a clever plan. I could walk out of the supermarket and wait in a place where I would not receive notification from the console.

    But if someone brings apples to the supermarket, there will be a signal in the waiting area, and then the supermarket is likely to have apples, and THEN I come out of the waiting area and wait for the opportunity to call my number.

    The apples might be snatched by other students who eat them, but at least it won’t waste too much time.

Just right next to the supermarket, there are many waiting areas for each fruit, there are six in total, which are: there is no waiting area for apples, there is no waiting area for watermelon, there is no waiting area for oranges. Apples fill the waiting area, watermelons fill the waiting area, oranges fill the waiting area.

Xiao Wang is very smart, went to the apple not waiting area, waiting for someone to send apple signal.

Then Sun went into the supermarket and bought five apples for the supermarket and got pocket money. He immediately notified apple that there was no waiting area, signaling “Apples in the supermarket!” But sun had not left the supermarket yet.

Xiao Wang received the signal in the waiting area and immediately walked out of the waiting area and waited for the number to be called so that he could finish his task of eating the apple. But unfortunately, before Xiao Wang got the chance, the apples were stolen by several other students, and then it was Xiao Wang’s turn.

Wang was also smart enough to consider the situation. Instead of taking apples directly, he re-queried the number of apples and found that the number of apples was 0. Then he repeated the previous steps and wang returned to the waiting area without apples.

The next time, wang kept apple didn’t move the waiting area and student id card waiting area, wang found to eat an apple too hard, must meet at the same time, apple didn’t sent the waiting area “supermarkets have apple” signals, license area at this time have a student id card, and on the operating table query out the number of apple is not zero.

Finally, one time. Wang successfully met all three conditions, and the number of apples seen on the operating table was 1! Xiao Wang is excitedly ready to press the purchase button, but at this time work station flash, suddenly appeared the number of others.

This person is a supermarket administrator, holding a special supermarket administrator card successfully entered the supermarket, took away the apples, at this time the number of apples became 0.

Then it was Wang’s turn to operate, but Wang did not know what had happened before, he clearly saw that the number of apples was 1. For the sake of insurance, Wang repeatedly inquired the number of apples, and found that it was still 1, so excited place under the purchase button!

So the console ordered apples from a storage area where there were no apples, something the system didn’t expect to happen, and the machine exploded, flattening the school.

Years later, the school was slowly rebuilt. The man who had built the desk had been shot and a well-paid man was hired to build it, and the problem was solved.

The supermarket runs smoothly, sometimes there is only one person in the supermarket, and sometimes there are three people in the supermarket, who are students, teachers and dormitory administrator aunt. They three people do not affect each other and live in peace. School life became rich again.

— — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — — — —

This story covers most of the core issues with Java multithreading, and I’ll tell it all over again.

There is a school (Java virtual machine), there are many many people (threads), we simply divided into students, teachers, and dormitory administrator aunt.

There is also a bizarre fruit supermarket in the middle of the school (the critical zone), with a warehouse for apples, watermelons and oranges (the protected resources in the critical zone).

People who come to this supermarket, on the one hand, can take the fruit and eat it, on the other hand, they can bring the fruit and pay back the money. Students can only eat or give apples, teachers can only have watermelons and the dorm lady can only give oranges.

The entrance and exit of this supermarket is also very well regulated. People who come to this supermarket must hold corresponding certificates (lock objects), students need to hold student ID cards, teachers need to hold teacher id cards, dormitory administrator aunt need to hold aunt id cards (different lock objects).

There is only one card for each of the three, and it is kept at the entrance of the supermarket in a collection area. Before entering the supermarket, people have to go to the collection area to get the corresponding certificate (to obtain the lock).

If the certificate is temporarily taken away by others and cannot be obtained (the lock fails to be obtained), you need to queue in the waiting area behind (synchronization queue SychronizedQueue) to wait for the certificate. There are also three waiting areas, namely student ID waiting area, teacher ID waiting area and aunt ID waiting area (each lock object corresponds to a synchronization queue).

Entering the supermarket is even more bizarre, whether to take fruit from the supermarket, or to bring fruit, all need to be controlled by a console (single-core CPU), and this console, at a time can only be operated by one person.

In order to prevent someone from occupying the console for too long, only one person is allowed to operate the console for 10 seconds (CPU time slice). After 10 seconds, an ID will be displayed on the screen, and only the person with this ID can operate the console (thread switching).

As for the selection of the number, teachers, students or the dormitory administrator aunt can not decide and intervene, only the console to decide (the operating system decides the thread switching and time allocation). Fortunately, everyone has their own account on the console (the thread’s working memory), and data that is interrupted halfway through the operation is not lost.

That’s the background of the story, and then all sorts of things happen at the school.

Let’s assume, first of all, that the people who come to this school are going to do things at the supermarket. First the person appears outside the school (thread state NEW), and the person enters the school (thread state RUNNABLE).

At one point, a number 2 appeared on the desk, which was announced to everyone on various school screens. So xiao Ming, a student with ID no. 2, saw his number and learned that he had gained the right to enter the supermarket operation console (CPU execution right), so he set out for the supermarket.

Xiao Ming first went to the door of the supermarket and asked the management of the identification office, “Give me a student CARD!” (Get lock). The administrator looked for a student ID card and gave it to Xiao Ming.

Xiao Ming got his student ID card and entered the supermarket smoothly (he succeeded in obtaining the lock and entered the critical area). He sat on the operating desk and logged in his account system (prepare the working memory and start to execute the critical area code).

The purpose of Xiao Ming’s visit is to take an apple, so he clicks the apple product icon, the system shows that there are four apples. So Ming took away the apples smoothly, and the system recorded the number of apples -1 and the new number of apples 3 into the total system library (code).

Then Xiao Ming went out of the supermarket (out of the critical area after the code execution), returned the student ID card to the identification office (release the lock), went out of the campus (thread state TERMINAL), disappeared in the crowd outside.

Then no. 3 was displayed on the console, again via the school’s big screen. Xiao Zhang, a student with ID no. 3, saw his number and learned that he had gained access to the supermarket’s operation console, so he set off for the supermarket.

Xiao Zhang and Xiao Ming did exactly the same thing, but Xiao Zhang was too slow. As soon as he finished clicking on the apple product icon, the system showed the next person’s number 5. At this point, Zhang is forced to terminate his operation and give up the console’s rights (thread switching).

Xiao Wang, a student with ID no. 5, went to the supermarket excitedly after receiving the notice and asked the management staff at the identification office, “Give me a student ID card!” .

The management staff searched and found that Ming had taken away the student ID card. They could only tell Wang, “Sorry, there is no student ID card at the moment, please queue up in the waiting area (synchronous queue) at the back of the student ID card.” Failed to obtain the lock. Xiao Wang had no choice but to obediently queue up (thread status).

This is the console showing number 3 again, which is just halfway through the operation. Xiao Zhang was still in the supermarket (did not release the lock) and did not need to re-enter, so he hurried to the operation desk to continue the operation (thread switch, continue to execute the interrupt code), took an apple, left the supermarket, and returned the student ID (release the lock).

At this time, the management staff of the id office received the student ID card and shouted to the student ID queue area behind, “There is a student ID card, people in line come and get it!” Notify the synchronization queue to dequeue.

When Wang no. 5, who was waiting in line, heard this, he came out of the queue and prepared to get the certificate and enter the supermarket. But at this time, the number displayed on the operating table is another student No. 10. Student No. 10 took away his student ID card, entered the supermarket and began to operate.

Operation to half, the time limit of the operating platform has come up again, showing Xiao Wang’s ID number 5. Wang just got out of the queue and finally got permission to proceed to the next step. He went to the card office and said, “Give me a student CARD!”

As the student ID card had been taken away by 10th, the administrator could only say, “Sorry, the student ID card is not available at the moment, please queue up in the waiting area of the student ID card at the back!”

When Xiao Wang saw that he had waited so long, he was beaten by others. He just wanted to say dirty words and thought of the famous saying of the school, “The world is not fair”, so he obediently went to the waiting area for the student ID card and continued to line up. (Unfair lock does not mean whoever waits the longest gets the lock)

And so on no. 10 out of the operation, but also the student card, Xiao Wang was received by the card office manager shout, “student card has, line up people come to take it!”

Wang walked out of the line, and the console finally showed wang’s number 5. This time, Xiao Wang successfully got his student ID card, entered the supermarket, sat on the operating table and logged in his own system.

Wang wanted to buy apples, so he clicked the button of Apple products, but the system showed that the number of apples was 0! Xiao Wang thought about it and had a plan:

  1. Stay in the supermarket and check the number of apples at the counter whenever possible until there are apples.

    But by staying in the supermarket, students who wanted to bring apples to the supermarket might not get their student ID cards, and they would never get apples. (Sychronized code block loop waiting)

  2. So Wang’s other idea is to go out of the supermarket, hand in his student ID card, and wait for the next opportunity to enter the supermarket to check the number of apples until there are apples.

    There was a chance of getting apples, but it was exhausting, and every trip was wasted if no one had delivered them to the supermarket at all. (Sychronized code block loop waiting)

  3. So Xiao Wang came up with a clever plan. I could walk out of the supermarket and go to a place to wait, where I would not be notified by the counter. If someone sends apples to the supermarket, the waiting area will send a signal (notify), then the supermarket may have apples, then I come out of the waiting area, waiting for the opportunity to call number.

  4. The apples might be snatched by other students who eat them, but at least it won’t waste too much time. (Waiting notification mechanism)

There are six waitqueues for each fruit: no apples, no watermelons and no oranges. Apples fill the waiting area, watermelons fill the waiting area, and oranges fill the waiting area (Condition variable).

Wang was smart enough to walk out of the supermarket and return his student ID (wait releases the lock), then go to the apple waiting area (WAIT) and wait for someone to send the apple signal (synchronous signal – wake up).

Then Sun went into the supermarket and bought five apples for the supermarket and got pocket money. He immediately notified apple that there was no waiting area, signaling, “There are apples in the supermarket! NotifyAll (AppleNotEmpty. NotifyAll) “, but sun is not out of the supermarket yet.

Xiao Wang received the signal in the waiting area and immediately walked out of the waiting area and waited for the number to be called so that he could finish his task of eating the apple. But unfortunately, before Xiao Wang got the chance, the apples were stolen by several other students, and then it was Xiao Wang’s turn.

Wang was also smart enough to take this situation into consideration. Instead of taking apples directly, he re-queried the number of apples (wait is generally combined with while condition) and found that the number of apples was 0. Then he repeated the previous steps and returned to the waiting area of apples running out again.

The next time, wang kept apple didn’t move the waiting area and student id card waiting area, wang found it difficult to do, in order to eat an apple must meet at the same time, apple didn’t sent the waiting area “supermarkets have apple” signals, license area at this time have a student id card, and on the operating table query out the number of apple is not zero.

Finally, one time. Wang successfully met all three conditions, and the number of apples seen on the operating table was 1! Xiao Wang is excitedly ready to press the purchase button, but at this time work station flash, suddenly appeared the number of others.

This person is a supermarket administrator, holding a special supermarket administrator card successfully entered the supermarket, took away the apples, at this time the number of apples became 0.

Then it was Wang’s turn to operate, but Wang did not know what had happened before, he clearly saw that the number of apples was 1. To be on the safe side, Wang checked the number of apples several times and found that it was still 1 (non-volatile variables do not guarantee visibility between threads), so he excitedly pressed the buy button!

The console then issues an order to fetch apples from a storage area where there are no apples at all, something the system never expected to happen, and the machine blows up and dies (throws a runtime exception, and the thread releases the lock and terminates).

A few years later, the former operator was fired, and the university hired a highly paid employee to build it, eliminating the previous problem (volatile).

Supermarket and smooth running, and sometimes only one supermarket (different threads into the same critical section will mutually exclusive lock object, only one thread can access), there are three people sometimes supermarket (the critical region of different lock object is not mutually exclusive), aunt were students, teachers, the dormitory administrator, three of them mutually affect and peaceful. School life became rich again.

At the end of the story, while it doesn’t explain all of concurrent programming and doesn’t always get the details right, it’s an interesting thought process

I hope you can also actively discuss the mistakes and imperfections in the story, and tell the story better together. Here are some of the things that appear in the story and the moral.