Four necessary conditions for Java multithreading deadlock

Four necessary conditions for deadlock

  1. Mutually exclusive conditions: A resource can only be used by one thread at a time .
  2. Request and hold conditions: For example, when requesting the second lock, keep the first lock of oneself and not release it.
  3. Non-deprivation conditions: The resources that the process has acquired (such as the locks that have been acquired), there is no outside force to deprive the lock.
  4. Loop waiting condition: When there are two threads, you are waiting for me to release the lock, and I wait for you to release the lock. When there are multiple threads, it is waiting end to end.
    For example, the following figure

The above four conditions are necessary conditions for deadlock to occur, that is, these four conditions must be met at the same time before deadlock occurs.

Interpretation of deadlock cases

For example, in the example of this article.
https://javaweixin6.blog.csdn.net/article/details/108460550 The
first condition, mutually exclusive condition. The
following are mutually exclusive conditions. There is only one static variable in the program running. synchronized The locks o1 and o2 in can only be held by one thread. The

second request and hold conditions, thread 1 holds lock o1 and requests lock o2. Thread 2 holds lock o2 and requests lock o1. And synchronizedthe feature is that it is not acquired When locked, the lock will not be released. The

third point is that the condition is not deprived. When waiting for each other's lock resources, there will be no extra power to deprive one party of the lock, only let them continue to wait.
Fourth Click the loop wait condition. When there are two threads, thread 1 and thread 2 wait for each other. When there are multiple threads, a loop wait is formed.

As long as one of the conditions is cracked, the deadlock will not occur.

Guess you like

Origin blog.csdn.net/qq_33229669/article/details/108481331