Learn about synchronization from the ground up in java-17.4 (2)-detailed explanation of competition conditions
In this chapter, we will discuss in detail the competition conditions.
1. Why does it cause competition?
The operation lacks atomicity.
2. What is atomicity?
The so-called atomic operation is an operation that will not be interrupted by the thread scheduling mechanism. Once this operation starts, it will continue to run until the end, and there will be no context switch (switch to another thread) in the middle ).
3. The procedure for breaking down the transfer in the previous chapter:
(1) read the balance of an account and compare the extracted amount
If (accounts [fromAccount] <money) {return ;}(2) Transfer xxx RMB from account
Accounts [fromAccount]-= money;
(3) transfer from account B to XXX RMB
Accounts [toAccount] + = money;
4. Because it is not atomic and multi-threaded, we can assume that:
(1) Now thread A has executed the First Step 2 above.
(2) Now thread B is started. Perform Step 1 and Step 2 on the same account.
(An error occurred at this time)
(3) thread A executes step 3.
(4) thread B executes step 3.
Loop ....
We only list the two threads working at the same time, but our test program has 20 threads. In reality, if there may be 20000 or even 2000000 threads, the data will be messed up directly.
5. steps:
6. Worse case
The probability of this error is determined by the time between Step 2 and Step 3. The longer the time, the higher the probability of error occurrence.
Summary: This chapter mainly discusses the competition conditions in detail.
This chapter is here. Thank you.