Java死锁

2018-07-20  本文已影响45人  WilsonMing

死锁

死锁,指两个或多个线程之间,由于互相持有对方需要的锁,而永久处于阻塞的状态。


死锁
public class DeadLockSimple extends Thread {
    private String first;
    private String second;

    public DeadLockSimple(String name, String first, String second) {
        super(name);
        this.first = first;
        this.second = second;
    }

    @Override
    public void run() {
        super.run();
        synchronized (first) {
            System.out.println(this.getName() + ",obtained1:" + first);

            try {
                Thread.sleep(1000L);
                synchronized (second) {
                    System.out.println(this.getName() + ",obtained2:" + second);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {
        //死锁检测
        ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
        Runnable dlCheck = new Runnable() {
            @Override
            public void run() {
                long[] threadIds = mxBean.findDeadlockedThreads();
                if (threadIds != null) {
                    ThreadInfo[] threadInfos = mxBean.getThreadInfo(threadIds);
                    System.out.println("Detected deadlock threads:");
                    for (ThreadInfo threadInfo : threadInfos) {
                        System.out.println(threadInfo.getThreadName());
                    }
                }
            }
        };
        ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(dlCheck,5L,10L, TimeUnit.SECONDS);
        //死锁示例
        String lockA = "lockA";
        String lockB = "lockB";
        DeadLockSimple t1 = new DeadLockSimple("thread1", lockA, lockB);
        DeadLockSimple t2 = new DeadLockSimple("thread2", lockB, lockA);
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出

thread2,obtained1:lockB
thread1,obtained1:lockA
Detected deadlock threads:
thread2
thread1

死锁检测:通过相关工具检测死锁。

产生死锁的四个必要条件

如何避免死锁

上一篇下一篇

猜你喜欢

热点阅读