找一个 wait() 方法让线程等待,使用 Object 中的 notify()的代码例子
时间: 2024-02-17 17:02:05 浏览: 25
好的,这是一个使用 wait() 和 notify() 方法的简单的代码例子:
```java
class MyThread extends Thread {
private Object lock;
public MyThread(Object lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
try {
System.out.println("线程开始等待...");
lock.wait();
System.out.println("线程被唤醒,继续执行。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
MyThread t1 = new MyThread(lock);
t1.start();
Thread.sleep(1000);
synchronized (lock) {
System.out.println("唤醒等待中的线程...");
lock.notify();
}
}
}
```
在上面的例子中,当 MyThread 线程启动后,它会进入 synchronized 块,并调用 lock.wait() 方法,进入等待状态。在 main 方法中,我们等待 1 秒钟后,调用 lock.notify() 方法,唤醒等待中的线程。这时 MyThread 线程就会继续执行,并输出“线程被唤醒,继续执行。”的信息。