首页 > 代码库 > Java 死锁

Java 死锁

什么是死锁?

当一个线程永远地持有一个锁,并且其他线程都尝试去获得这个锁时,那么它们将永远被阻塞,当线程A持有锁1想获取锁2,当线程B持有锁2想获取锁1 这种情况下就会产生2个线程一直在阻塞等待其他线程释放锁1 锁2 就会造成死锁。

下面我们来看一下死锁的示例:

package cn.com.example;

/**
 * Created by Jack on 2017/2/10.
 */
public class DeadLock {

    private static Object o1 = new Object(), o2 = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(new DeadLockThread(1, o1, o2));
        Thread t2 = new Thread(new DeadLockThread(2, o1, o2));

        t1.start();
        t2.start();
    }
}

class DeadLockThread implements Runnable {
    private int i;

    private Object o1;

    private Object o2;

    public DeadLockThread(int i, Object o1, Object o2) {
        this.i = i;
        this.o1 = o1;
        this.o2 = o2;
    }

    @Override
    public void run() {
        if (i == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("i = 1 synchronized o1");
                synchronized (o2) {
                    System.out.println("i = 1 synchronized o2");
                }
            }
        } else if (i == 2) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("i = 2 synchronized o2");
                synchronized (o1) {
                    System.out.println("i = 2 synchronized o1");
                }
            }
        }
    }
}

输出:

i = 1 synchronized o1
i = 2 synchronized o2

后面什么都不输出了, 为什么要 Thread.sleep(500);  是怕 某个线程先运行 抢占了 o1 o2 的锁。

 

Java 死锁