一个简单的例子理解wait和notify两个方法

public class waitnotify {
	public static void main(String[] args) {
		Object obj = new Object();
		Thread t1=new Thread(()-> {
				synchronized (obj) {
					System.out.println("t1获得了obj的监视器");
					try {
						System.out.println("t1准备被阻塞了并且释放锁");
						obj.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("t1获得了obj的监视器,被唤醒了");
				}
		});
		t1.start();
		Thread t2=new Thread(()-> {
				synchronized (obj) {
					System.out.println("这点证明了wait会释放锁,即将准备唤醒被阻塞的t1");
					obj.notify();
					System.out.println("我唤醒了t1但是我还会把我接下来的代码执行完");
					System.out.println("还在t2");
					System.out.println("还在t2");
					System.out.println("还在t2");
					System.out.println("还在t2");
					System.out.println("还在t2");
					System.out.println("还在t2");
					try {
						Thread.sleep(5000);
						System.out.println("我已经被阻塞5秒了还没轮到t1,所以t1要等我执行完");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
		});
		t2.start();
	}
}

运行结果:
简单的例子理解wait()和nodify()

相关文章:

  • 2021-11-07
  • 2022-03-04
  • 2022-01-21
  • 2021-10-24
  • 2021-07-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-22
  • 2021-08-04
  • 2022-01-05
  • 2021-08-21
相关资源
相似解决方案