现在的位置: 首页 > 综合 > 正文

Java学习整理之Object的wait和notify方法

2018年02月06日 ⁄ 综合 ⁄ 共 2756字 ⁄ 字号 评论关闭

wait和notify概念理解

例如:线程A

   synchronized(obj) {

               while(!condition) {

                         obj.wait();

                 }

                obj.doSomething();

  }

当线程A获得了obj锁后,发现条件condition不满足,无法继续下一处理,于是线程A就wait()。在另一线程B中,如果B更改了某些条件,使得线程A的condition条件满足了,就可以唤醒线程A。

线程B

      synchronized(obj) {

              condition = true;

              obj.notify();

        }

需要注意的概念是:  

   1.调用obj的wait(), notify()方法前,必须获得obj锁,也就是必须写在synchronized(obj) {……} 代码段内。  

   2.调用obj.wait()后,线程A就释放了obj的锁,否则线程B无法获得obj锁,也就无法在synchronized(obj) {……} 代码段内唤醒A.  

   3.当obj.wait()方法返回后,线程A需要再次获得obj锁,才能继续执行。  

   4.如果A1,A2,A3都在obj.wait(),则B调用obj.notify()只能唤醒A1,A2,A3中的一个(具体哪一个由JVM决定)。  

   5.obj.notifyAll()则能全部唤醒A1,A2,A3,但是要继续执行obj.wait()的下一条语句,必须获得obj锁,因此,A1,A2,A3只有一个有机会获得锁继续执行,例如A1,其余的需要等待A1释放obj锁之后才能继续执行。

   6.当B调用obj.notify/notifyAll的时候,B正持有obj锁,因此,A1,A2,A3虽被唤醒,但是仍无法获得obj锁。直到B退出synchronized块,释放obj锁后,A1,A2,A3中的一个才有机会获得锁继续执行。

使用示例

有了上面的理解,还得强调下面的几点:

  1. 任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。
  2. 无论是执行对象的wait、notify还是notifyAll方法,必须保证当前运行的线程取得了该对象的控制权(monitor)
  3. 如果在没有控制权的线程里执行对象的以上三种方法,就会报java.lang.IllegalMonitorStateException异常。
  4. JVM基于多线程,默认情况下不能保证运行时线程的时序性

public class NotifyTest {
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Main Thread Run!");
		PersonIn person=new PersonIn();
		person.setName("default");
		NotifyThread notifyThread = new NotifyThread("notify", person);
		WaitThread waitThread01 = new WaitThread("waiter01", person);
		WaitThread waitThread02 = new WaitThread("waiter02", person);
		WaitThread waitThread03 = new WaitThread("waiter03", person);
		notifyThread.start();
		waitThread01.start();
		waitThread02.start();
		waitThread03.start();
	}

}
class NotifyThread extends Thread {
	private String name;
	private Object obj;

	public NotifyThread(String name, Object obj) {
		super(name);
		this.name = name;
		this.obj = obj;
	}

	public void run() {
		try {
			sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (obj) {
			((PersonIn)obj).setName("lxq");
			obj.notifyAll();
		}
	}
};

class WaitThread extends Thread {
	private String name;
	private Object obj;

	public WaitThread(String name, Object obj) {
		super(name);
		this.name = name;
		this.obj = obj;
	}

	public void run() {
		synchronized (obj) {
			while (((PersonIn)obj).getName().equals("default")) {
				System.out.println(getName() + " begin waiting!");
				long waitTime = System.currentTimeMillis();
				try {
					obj.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				waitTime = System.currentTimeMillis() - waitTime;
				System.out.println("wait time :" + waitTime);
			}
			System.out.println(getName() + " end waiting!");
		}
	}
}
class PersonIn{
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

注意,如果原理传进去一个“true”的flag,在同步块中做如下处理:

flag="false";

flag.notify();

对在同步块中对flag进行了赋值操作,使得flag引用的对象改变,这时候再调用notify方法时,因为没有控制权所以会抛出java.lang.IllegalMonitorStateException异常。为了改进,所以代码中将flag改成一个JavaBean,然后更改它的属性不会影响到flag的引用。

抱歉!评论已关闭.