public class Thread implements Runnable { public static native void sleep(long millis) throws InterruptedException;}public class Object { public final native void wait(long timeout) throws InterruptedException;}3.1 验证 sleep() 不开释锁
@Slf4jpublic class Demo { static final Object obj = new Object(); public static void main(String[] args) throws InterruptedException { new Thread(() -> { synchronized (obj) { log.debug("start..."); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("do something..."); } }).start(); TimeUnit.SECONDS.sleep(1); // main 线程想获取锁,并实行逻辑 synchronized (obj) { log.debug("run..."); } }}实行效果
22:16:16.687 [Thread-0] DEBUG com.example.concrete.Demo - start...22:16:19.691 [Thread-0] DEBUG com.example.concrete.Demo - do something...22:16:19.691 [main] DEBUG com.example.concrete.Demo - run...