死锁

阅读更多
/**
 * 死锁
 */
public class DeadLockDemo {
    private static Object lockA = new Object();
    private static Object lockB = new Object();

    private static void startThreadA(){
        Thread aThread = new Thread(){
            @Override
            public void run() {
                synchronized (lockA) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    synchronized (lockB) {}
                }
            }
        };
        aThread.start();
    }

    private static void startThreadB(){
        Thread bThread = new Thread(){
            @Override
            public void run() {
                synchronized (lockB) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    synchronized (lockA) {}
                }
            }
        };
        bThread.start();
    }

    public static void main(String[] args) {
        startThreadA();
        startThreadB();
    }

/**
 * 1.尽量避免同时持有多个锁,或按照相同的顺序去申请锁
 * 2.使用显示锁里的tryLock、tryLock(long time, TimeUnit unit)。
 *   可以在获取不到锁的时候,释放已经持有的锁,
 *   然后再次尝试获取锁或干脆放弃,避免死锁。
 * 3.通过jstack命令发现死锁
 */
}

你可能感兴趣的:(死锁)