关于object的wait和notity

起初想测试下,object的notifyAll和notify方法,关于notifyAll和notify,jdk的说明文档已经讲的很清楚了,这里再说明下

notifyAll是唤醒在该对象上所有等待该对象monitor的线程。关于monitor,其实还是有些说法的,Java对象是天生的Monitor,这句话大家应该好好理解下,可以参考http://www.cnblogs.com/tomsheep/archive/2010/06/09/1754419.html。

* Wakes up all threads that are waiting on this object's monitor. A
* thread waits on an object's monitor by calling one of the
* {@code wait} methods.

notify是随机唤醒某个在该对象上等待monitor的线程。
* Wakes up a single thread that is waiting on this object's
* monitor. If any threads are waiting on this object, one of them
* is chosen to be awakened. The choice is arbitrary and occurs at
* the discretion of the implementation. A thread waits on an object's
* monitor by calling one of the {@code wait} methods.

起初,代码上这样写的:public class TestObjectNotify {
   private static Object object = new Object();
public static void main(String[] args) {
final int i = 0;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
beginWait(i);
}
}) ;
thread.start();

final int j = 1;
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
beginWait(j);
}
}) ;
thread2.start();

final int k = 8;
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
beginWait(k);
}
}) ;
thread3.start();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----------notifyAll-------------");

object.notifyAll();
}

public static void beginWait(int i) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}

public static void beginNotify() {
System.out.println("-----------notify-------------");
object.notify();
}
}

当运行的时候,熟悉object的notify和notifyAll的同学可能已经看到问题了,会报一个异常
java.lang.IllegalMonitorStateException

其实在调用这三个方法的时候,一定要获取到该对象的锁,才能正确调用该方法,
后来改为如下的方式,就没问题了。关于具体原因,可以参考 http://www.cnblogs.com/techyc/p/3272321.html
synchronized (object) {
object.notifyAll();
}
synchronized (object) {
object.wait();
}
 
posted @ 2017-02-08 18:18  一匹河马  阅读(1271)  评论(0编辑  收藏  举报