Detailed explanation of Java synchronized nested usage code

When synchronized is used too much, it may cause deadlock. What's the matter with deadlock. First look at the following code to realize Deadlock:

The synchronized synchronization of the above code causes a deadlock. A deadlock is that two or more threads wait for each other's completion at the same time, and the program cannot continue to execute. Before interpreting the code, first understand what synchronized is all about. Synchronized defines synchronization, so what is synchronized and what is synchronized?

First, we need to know what a lock is. In Java, every object has an internal lock. If a method or code block is declared with synchronized, the lock of the object will protect the whole method or code block. To call this method or execute this code block, you must obtain the lock of the object. Moreover, only one thread object can execute protected code at any time

In the above code, after thread Th1 starts, he obtains the lock of A. at the same time, when it is dormant, he will apply for the lock of B. at this time, his lock of a is not abandoned. After thread Th2 starts, he obtains the lock of B. at the same time, when it is dormant, he will apply for the lock of A. at this time, his b lock is not abandoned.

Both parties hold their own locks and do not give up, but apply for the other party's lock at the same time. Therefore, a deadlock is caused at this time.

Synchronization refers to the synchronization of threads and objects. The threads and objects are bound to obtain the lock of the object.

Note: through the above code, it can be found that the necessary condition of deadlock is not to give up the existing lock, but to apply for a new lock at the same time. Therefore, to achieve deadlock, there will be synchronized nesting.

In this way, more than two locks can be operated at the same time, resulting in deadlock.

summary

The above is all about the detailed explanation of Java synchronized nested use code in this article. I hope it will be helpful to you.

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
分享
二维码
< <上一篇
下一篇>>