wait(long arg)方法的功能是等待一段时间,在这段时间内是否有线程对持有的锁对象进行唤醒,如果超过了这段时间,该锁就自动唤醒。
class MyRunnable implements Runnable {
private Object lock;
public MyRunnable (Object lock){
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
System.out.println(“begin wait start== ” + System.currentTimeMillis());
lock.wait(5000);
System.out.println(“end wait == ” + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.toString();
}
}
}
public class TestClass1{
public static void main(String[] args) {
private Object lock = new Object();
Thread thread = new Thread(new MyRunnable(lock));
thread.start();
}
}
执行结果如下:
begin wait start== 1469189350089
5s过后锁自动唤醒
end wait == 1469189355090
下面演示提前通过其他的线程唤醒处于等到的锁。
class MyRunnableTwo implements Runnable {
private Object lock ;
public MyRunnableTwo ( Object lock ){
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
System.out.println(“begin notify start== ” + System.currentTimeMillis());
lock.notify();
System.out.println(“end notify == ” + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.toString();
}
}
}
public class TestClass2{
public static void main(String[] args) {
private Object lock = new Object();
//启动线程1,然后线程进入5s阻塞状态
Thread thread1 = new Thread(new MyRunnable(lock));
thread1 .start();
//睡眠3s,然后调用唤醒线程,提前唤醒锁
try {
Thread.sleep(3000)
}
} catch (InterruptedException e) {
e.toString();
}
//睡眠3s,然后调用唤醒线程,提前唤醒锁
Thread thread2 = new Thread(new MyRunnableTwo(lock));
thread2.start();
}
}
执行结果:
begin wait start== 1469190695863
begin notify start== 1469190698871
end notify == 1469190698871
end wait == 1469190698871