package com.roocon.thread.t6; public class Demo3 { private Object obj1 = new Object(); private Object obj2 = new Object(); public void a(){ synchronized (obj1){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj2){ System.out.println("a"); } } } public void b(){ synchronized (obj2){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj1){ System.out.println("b"); } } } public static void main(String[] args) { Demo3 demo3 = new Demo3(); new Thread(new Runnable() { @Override public void run() { demo3.a(); } }).start(); new Thread(new Runnable() { @Override public void run() { demo3.b(); } }).start(); } }
运行结果:
控制台一直在运行,但是无任何输出。
通过命令检测是否真的发生了死锁:
点击线程,检测死锁: