wait、notify为什么要放在同步代码块中

wait是让使用wait方法的对象等待,暂时先把对象锁给让出来,给其它持有该锁的对象用,其它对象用完后再告知(notify)等待的那个对象可以继续执行了,因此,只有在synchronized块中才有意义(否则,如果大家并不遵循同步机制,那还等谁呢?根本没人排队,也就谈不上等待和唤醒了)
以下是一个例子,用以展示这种机制:

public class ThreadA {
public static void main(String[] args) {
	ThreadB b = new ThreadB();
	//主线程中启动另外一个线程
	b.start();
	synchronized(b) {
		try {
			System.out.println("Waiting for b to complet...");
			b.wait();
			System.out.println("ThreadB is Completed.Now back to main");
		}catch(InterruptedException e) {
			
		}
	}
	System.out.println("Total is :"+b.total);
}
}

class ThreadB extends Thread{
	int total;
	public void run() {
		synchronized(this) {
			System.out.println("ThreadB is running..");
			for(int i =0;i<=100;i++) {
				total +=i;
			}
			System.out.println("total is"+total);
			notify();
		}
	}
}

运行结果:
在这里插入图片描述

发布了68 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42913025/article/details/101038667
今日推荐