package com.gaopeng.multithread;
/**
   * 简单实现一个死锁例子
 * 
 * @author gaopeng
 *
 */
public class DeadLockTest {
    // 创建资源
    private static Object resourceA = new Object();
    private static Object resourceB = new Object();
    public static void main(String[] args) {
        // 创建线程A
        Thread threadA = new Thread(new 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");
                    }
                }
            }
        });
        // 创建线程B
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取resourceA共享资源的监视器锁
                synchronized (resourceB) {
                    System.out.println(Thread.currentThread() + " get ResourceB");
                    try {
                        Thread.sleep(1000);
                    } 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();
    }
}
运行结果如下:

两个线程一直等待对方释放持有的锁,然后一直等到死亡。。。
中间加睡眠时间,是为了防止线程一运行就获得两个对象的锁。
如何避免死锁的产生呢???
造成死锁的原因其实和申请资源的顺序有很大关系,使用资源申请的有序性原则就可以避免死锁。
下面给几个建议:
避免一个线程同时获取多个锁;
避免一个线程在锁内同时占据多个资源,尽量保证每个锁只占据一个资源;
尝试使用定时锁,使用lock.tryLock(timeout)来代替使用内部锁机制;
对于数据库锁,加锁和解锁必须在一个数据库连接里,否则会出现解锁失败的情况。
来源:https://www.cnblogs.com/gaopengpy/p/12208543.html