Detailed examples of deadlock in Java

Detailed examples of deadlock in Java

First look at the code to explain

The above is the code part. If there is no deadlock, you can add while (true) under if, which will inevitably deadlock. Let's explain below.

This is only for understanding deadlock and interview. Two objects a and B are created only for deadlock. Thread T1 runs (T1. Start ()), and thread T1 needs to continue to execute to get lock B after getting lock a, while thread T2 runs (T2. Start ()) to get lock B and want to continue to get lock a to continue to execute. This forms a deadlock and holds the required lock objects opposite each other.

For an interview, you can simply write down that two threads and two lock objects are nested with each other. At least two states are executed at the same time. If you can't do it once, you can execute it many times. You can also add a loop outside the lock to let the thread run many times, and it will deadlock. Because it runs once, there may be accidents. After the first thread is executed, the lock object is released, and the second thread comes in for execution, So there is an accidental phenomenon.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>