Package com.gaopeng.multithread; / ** * achieve a simple example of deadlock * * @author gaopeng * * / public class DeadLockTest { // Create a Resource Private static Object resourceA = new new Object (); Private static Object ResourceB = new new Object (); public static void main (String [] args) { // create a thread A the thread ThreadA = new new the thread ( new new the Runnable () { @Override public void run() { // 获取resourceA共享资源的监视器锁 synchronized (resourceA) { System.out.println(Thread.currentThread() + " get ResourceA"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + " waiting get ResourceB"); synchronized (resourceB) { System.out.println(Thread.currentThread() + " get ResourceB"); } } } }); // Create a thread B the Thread ThreadB = new new the Thread ( new new the Runnable () { @Override public void RUN () { // Get resourceA shared resource monitor lock the synchronized (ResourceB) { the System.out .println (Thread.currentThread () + "GET ResourceB is" ); the try { the Thread.sleep ( 1000 ); } the catch (InterruptedException E) { e.printStackTrace (); } System.out.println(Thread.currentThread() + " waiting get ResourceA"); synchronized (resourceA) { System.out.println(Thread.currentThread() + " get ResourceA"); } } } }); // 启动线程 threadA.start(); threadB.start(); } }
Results are as follows:
Two threads have been waiting for each other to release the locks held, and then wait until death. . .
The middle of sleep time, in order to prevent a run on the thread acquires the lock of the two objects.
How to avoid deadlock produce it? ? ?
In fact, the cause deadlock and order of application has a lot of resources, use of resources application of the principles of orderliness can avoid deadlock.
Here are several suggestions to:
Avoid a thread simultaneously acquire multiple locks;
Avoid a thread occupy multiple resources simultaneously in the lock, try to ensure that each lock occupies only one resource;
Try using time lock, using lock.tryLock (timeout) instead of using the internal locking mechanism;
For database locks, locking and unlocking must be a database connection, otherwise the situation will appear unsuccessful.