Deadlock: When a thread holds a lock forever, and other threads try to acquire the lock, they will always be blocked. For example, thread 1 already holds a lock and wants to get a B lock while thread 2 holds a B lock and tries to acquire a lock, then these two threads will wait forever.
Let's look at a simple example of a deadlock:
1 Public classdeadlocktest2 {3 Private StaticObject A =NewObject (), B =NewObject ();4 5 Public Static voidMain (string[] args)6 {7 NewThread (() {8SYSTEM.OUT.PRINTLN ("Thread 1 starts executing ...");9 synchronized(A)Ten { One Try A { -SYSTEM.OUT.PRINTLN ("Thread 1 gets a lock"); - //sleeps two seconds so that thread 2 has time to get the B lock . theThread.Sleep (2000); -}Catch(Exception e) - { - e.printstacktrace (); + } - synchronized(B) + { ASYSTEM.OUT.PRINTLN ("Thread 1 Get B lock"); at } - } - }). Start (); - - NewThread (() { -SYSTEM.OUT.PRINTLN ("Thread 2 starts executing ..."); in synchronized(B) - { to Try + { -SYSTEM.OUT.PRINTLN ("Thread 2 get B lock"); the //sleep two seconds let thread 1 have time to get a lock *Thread.Sleep (2000); $}Catch(Exception e)Panax Notoginseng { - e.printstacktrace (); the } + synchronized(A) A { theSYSTEM.OUT.PRINTLN ("Thread 2 gets a lock"); + } - } $ }). Start (); $ - } -}
Operation Result:
From the running results can be seen, thread 1 got a lock, and try to get the B lock, while thread 2 got the B lock and try to get a lock, at this time thread 1 and thread 2 into the infinite Wait, forming a deadlock.
So how do you prevent deadlocks? Here are a few common methods:
1. Avoid one thread acquiring multiple locks at the same time
2, avoid a thread in the lock to occupy multiple resources at the same time, as far as possible to ensure that each lock occupies only one resource
3, try to use the timing lock, use Lock.trylock to replace the use of built-in lock.
For details, refer to "Java Concurrency Programming"
A simple example of deadlock in Java and its avoidance