public class Test { static Object o1 = new Object(); static Object o2 = new Object(); public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { synchronized (o1) { System.out.println("線程1鎖o1"); try { Thread.sleep(1000);//讓當前線程睡眠,保證讓另外一線程獲得o2,防止這個線程啓動一下連續得到o1和o2兩個對象的鎖。 synchronized (o2) { System.out.println("線程1鎖o2"); } } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { synchronized (o2) { System.out.println("線程2鎖o2"); synchronized (o1) { System.out.println("線程2鎖o1"); } } } }).start(); } }