死锁例子
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了死锁例子相关的知识,希望对你有一定的参考价值。
线程T1持有锁A,再去获取锁B,线程T2持有锁B,再去获取锁A,这时候线程T1获取不到锁B,线程T2获取不到锁A,就发生死锁了
public class DeadLock { private static final Object lockA = new Object(); private static final Object lockB = new Object(); public static void main(String[] args) { new Thread(() -> { synchronized (lockA) { System.out.println(Thread.currentThread().getName() + "获得锁A"); try { Thread.sleep(2_000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lockB) { System.out.println(Thread.currentThread().getName() + "获得锁B"); } } }, "【线程一】").start(); new Thread(() -> { synchronized (lockB) { System.out.println(Thread.currentThread().getName() + "获得锁B"); try { Thread.sleep(2_000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lockA) { System.out.println(Thread.currentThread().getName() + "获得锁A"); } } }, "【线程二】").start(); } }
以上是关于死锁例子的主要内容,如果未能解决你的问题,请参考以下文章