Object.wait()与Object.notify()的用法详细解析
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Object.wait()与Object.notify()的⽤法详细解析
wait、notify和notifyAll⽅法是Object类的final native⽅法。
所以这些⽅法不能被⼦类重写,Object类是所有类的超类,因此在程序中有以下三种形式调⽤wait等⽅法。
复制代码代码如下:
wait();//⽅式1:
this.wait();//⽅式2:
super.wait();//⽅式3
解除所有那些在该对象上调⽤wait⽅法的线程的阻塞状态。
该⽅法只能在同步⽅法或同步块内部调⽤。
如果当前线程不是锁的持有者,该⽅法抛出⼀个IllegalMonitorStateException异常。
随机选择⼀个在该对象上调⽤wait⽅法的线程,解除其阻塞状态。
该⽅法只能在同步⽅法或同步块内部调⽤。
如果当前线程不是锁的持有者,该⽅法抛出⼀个IllegalMonitorStateException异常。
导致线程进⼊等待状态,直到它被其他线程通过notify()或者notifyAll唤醒。
该⽅法只能在同步⽅法中调⽤。
如果当前线程不是锁的持有者,该⽅法抛出⼀个IllegalMonitorStateException异常。
导致线程进⼊等待状态直到它被通知或者经过指定的时间。
这些⽅法只能在同步⽅法中调⽤。
如果当前线程不是锁的持有者,该⽅法抛出⼀个IllegalMonitorStateException异常。
Object.wait()和Object.notify()和Object.notifyall()必须写在synchronized⽅法内部或者synchronized块内部,这是因为:这⼏个⽅法要求当前正在运⾏object.wait()⽅法的线程拥有object的对象锁。
即使你确实知道当前上下⽂线程确实拥有了对象锁,也不能将object.wait()这样的语句写在当前上下⽂中。
如:
复制代码代码如下:
package edu.sjtu.erplab.ObjectTest;
class A
{
public synchronized void printThreadInfo() throws InterruptedException
{
Thread t=Thread.currentThread();
System.out.println("ThreadID:"+t.getId()+", ThreadName:"+t.getName());
}
}
public class ObjectWaitTest {
public static void main(String args[])
{
A a=new A();
//因为printThreadInfo()⽅法抛出InterruptedException异常,所以这⾥必须使⽤try-catch块
try {
a.printThreadInfo();
a.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
程序运⾏会报错,运⾏结果如下:
ThreadID:1, ThreadName:main
Exception in thread "main" ng.IllegalMonitorStateException
at ng.Object.wait(Native Method)
at ng.Object.wait(Object.java:485)
at edu.sjtu.erplab.ObjectTest.ObjectWaitTest.main(ObjectWaitTest.java:24)
正确的写法应该是
复制代码代码如下:
package edu.sjtu.erplab.ObjectTest;
class A
{
public synchronized void printThreadInfo() throws InterruptedException
{
Thread t=Thread.currentThread();
System.out.println("ThreadID:"+t.getId()+", ThreadName:"+t.getName());
// this.wait();//⼀直等待
this.wait(1000);//等待1000ms
// super.wait(1000);
}
}
public class ObjectWaitTest {
public static void main(String args[])
{
A a=new A();
//因为printThreadInfo()⽅法抛出InterruptedException异常,所以这⾥必须使⽤try-catch块 try {
a.printThreadInfo();
//a.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread t=Thread.currentThread();
System.out.println("ThreadID:"+t.getId()+", ThreadName:"+t.getName());
}
}。