In this chapter, we will discuss the competition conditions in detail.
1. Why is there a competitive condition?
Because the operation lacks atomicity.
2. What is atomicity?
Atomic operations are operations that are not interrupted by the thread-scheduling mechanism, which, once started, runs until the end. There will be no context switch in between (switch to a thread).
3. Steps to break down the previous chapter transfer:
(1) Read the remaining amount of an account. Amount extracted from the control
if (Accounts[fromaccount] < money) {return;}
(2) from a account transfer xxx Yuan
Accounts[fromaccount]-= money;
(3) Transfer from B account to xxx yuan
Accounts[toaccount] + = money;
4. Because it is not atomic and is multithreaded, we are able to:
(1) Now thread A has run the first and second steps above
(2) thread B is now started. Take the first second step on the same account
(This time has gone wrong)
(3) Thread A runs the third step
(4) thread B then run the third step
Cycle....
We only listed two threads at the same time, but our test program opened 20 threads. If the reality is that it could be 20000 or even 2 million threads, the data is just going to get out of hand.
5. Step diagram:
6. A worse situation
Because the probability of determining this error is controlled by the time between steps 2 through 3, the longer the time, the higher the probability of the error to occur.
Summary: This chapter mainly discusses the competition conditions in detail.
This chapter is here, thank you.
-----------------------------------
Folder
From the beginning to know java-17.4 specific explanation synchronization (2)-specific explanation of competitive conditions