Object对象有三个等待函数,可以使当前线程等待,释放本对象的资源,直到被中断或者唤醒,或者等待的时长达到设置的时长:
wait() 相当于 wait(0L, 0)
wait(long timeoutMillis) 相当于wait(long timeoutMillis, 0)
wait(long timeoutMillis, int nanos)
如果timeoutMillis和nanos都等于0,那么就一直等待,直到被唤醒。
当前线程必须拥有该对象的监视器锁(monitor lock)。
代码示例:
package com.thb;
import java.util.concurrent.TimeUnit;
public class Demo5 {
public static void main(String[] args) {
Demo5 lock = new Demo5();
// 创建一个线程
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("进入线程: " + Thread.currentThread().getName());
try {
System.out.println(Thread.currentThread().getName() + " 等待 ...");
// 等待
lock.wait();
// 被唤醒后打印
System.out.println(Thread.currentThread().getName() + " 被唤醒");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("离开线程: " + Thread.currentThread().getName());
}
}, "thread1");
// 启动线程
thread1.start();
// 创建另外一个线程
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("进入线程: " + Thread.currentThread().getName());
try {
// 睡眠5秒钟
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 唤醒其它一个线程");
// 唤醒其它在该对象上等待的一个线程
lock.notify();
System.out.println("离开线程: " + Thread.currentThread().getName());
}
}, "thread2");
// 启动线程
thread2.start();
System.out.println("当前线程: " + Thread.currentThread().getName());
}
}
运行输出:
当前线程: main
进入线程: thread1
thread1 等待 ...
进入线程: thread2
thread2 唤醒其它一个线程
离开线程: thread2
thread1 被唤醒
离开线程: thread1