Closed mysterin closed 5 years ago
当一个线程试图获取锁, 这个锁被其他线程持有, 当前线程就进入阻塞. 示例: blocking-thread线程会进入阻塞.
blocking-thread
@Test public void blocking() { Object obj = new Object(); Thread thread = new Thread(()->{ try { Thread.sleep(1000); synchronized (obj) { System.out.println("thread...sync"); } } catch (InterruptedException e) { e.printStackTrace(); } }, "blocking-thread"); thread.start(); synchronized (obj) { while (true); } }
当前线程等待其他线程发来通知, 收到通知后可能会继续执行, 也有可能去获取锁进入阻塞. 比如Object.wait(), Thread.join(), 示例: waiting-thread线程会进入等待.
Object.wait()
Thread.join()
waiting-thread
@Test public void waiting() throws InterruptedException { Object obj = new Object(); Thread thread = new Thread(() -> { synchronized (obj) { System.out.println("waiting-thread"); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "waiting-thread"); thread.start(); Thread.sleep(1000); synchronized (obj) { while (true); } }
阻塞
当一个线程试图获取锁, 这个锁被其他线程持有, 当前线程就进入阻塞. 示例:
blocking-thread
线程会进入阻塞.等待
当前线程等待其他线程发来通知, 收到通知后可能会继续执行, 也有可能去获取锁进入阻塞. 比如
Object.wait()
,Thread.join()
, 示例:waiting-thread
线程会进入等待.