package com.basic; /** * @program JavaBooks * @description: æ»éçæ¨¡æ * @author: mf * @create: 2020/01/09 13:57 */ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * ç¨çº¿ç¨æ± 模æï¼æ¯è¾æ¹ä¾¿ä¸äº */ public class T31 { private static Object res1 = new Object(); // èµæº1 private static Object res2 = new Object(); // èµæº2 public void m1() { synchronized (res1) { // å ç¨res1çé System.out.println(Thread.currentThread().getName() + " get res1"); try { Thread.sleep(1000); // å»¶æ¶ä¸ä¼ï¼çå¾ m2çæ¹æ³å ç¨res2 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("waiting get res2"); synchronized (res2) { System.out.println(Thread.currentThread().getName() + " get res2"); } } } public void m2() { synchronized (res2) { // å ç¨res2çé System.out.println(Thread.currentThread().getName() + " get res2"); try { Thread.sleep(1000); // } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("waiting get res1"); synchronized (res1) { System.out.println(Thread.currentThread().getName() + " get res1"); } } } public static void main(String[] args) { T31 t31 = new T31(); ExecutorService service = Executors.newCachedThreadPool(); service.execute(() -> t31.m1()); service.execute(() -> t31.m2()); } }