Java死锁示例

模拟2种出现死锁的方式
(1)锁资源互斥(锁资源被占用)
(2)读写锁互斥性

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 死锁
 *
 * @Ahthor luohq
 * @Date 2020-07-23
 */
public class Deadlock {


    public static void main(String[] args) {
        deadLock1();
        //deadLock2();
        //wrLockDowngrade();
    }


    /**
     * 死锁 - 资源互斥
     */
    public static void deadLock1() {
        Object lock1 = new Object();
        Object lock2 = new Object();

        new Thread(() -> {
            synchronized (lock1) {
                System.out.println("thread1 get lock1");
                //睡眠5秒(模拟进行耗时的操作,同时以使thread2优先获取lock2)
                sleep(5000L);
                synchronized (lock2) {
                    System.out.println("thread1 get lock2");
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lock2) {
                System.out.println("thread2 get lock2");
                sleep(5000L);
                synchronized (lock1) {
                    System.out.println("thread2 get lock1");
                }
            }
        }).start();
    }

    /**
     * 读写锁死锁 - 获取写锁后无法再获取读锁
     *
     * 1.读锁支持共享(可同时获取读锁、获取读锁后无法再获取写锁)
     * 2.写锁排他锁(获取写锁后无法再获取写锁、读锁)
     * 3.支持锁降级(写锁 -> 读锁)
     * 4.不支持锁升级(读锁 -> 写锁)
     */
    public static void deadLock2() {
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();
        ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();

        new Thread(() -> {
            rLock.lock();
            System.out.println("thread1 get rLock");
            wLock.lock();
            System.out.println("thread1 get wLock");
            rLock.unlock();
            wLock.unlock();
        }).start();

    }

    /**
     * 锁降级 - 写锁降级为读锁
     * 同时ReentrantReadWriteLock支持线程内重入(若不支持重入则获取锁后,在同线程内再次获取锁则出现死锁)
     */
    public static void wrLockDowngrade() {
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();
        ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();

        /** 【锁降级】可以正常执行:同一个线程中获取写锁 -> 获取读锁 -> 释放写锁 -> 释放读锁 */
        new Thread(() -> {
            wLock.lock();
            System.out.println("thread2 get wLock");
            rLock.lock();
            System.out.println("thread2 get rLock");
            wLock.unlock();
            rLock.unlock();
        }).start();

    }

    public static void sleep(Long mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java)