java类下的wait方法怎么使用
时间: 2023-05-31 13:04:51 浏览: 53
Java中的wait方法是Object类中的一个方法,用于线程间的协调和通信。wait方法会使当前线程进入等待状态,直到其他线程调用notify或notifyAll方法唤醒它。
wait方法的使用步骤如下:
1. 在使用wait方法的代码中获取对象的锁。
2. 调用wait方法,使当前线程进入等待状态。
3. 在其他线程中获取相同对象的锁,并调用notify或notifyAll方法唤醒等待的线程。
4. 等待线程被唤醒后,重新获取锁并执行相应的操作。
以下是一个简单的示例代码:
```java
public class WaitDemo {
public synchronized void waitForSignal() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " is waiting for signal");
wait(); // 等待其他线程的唤醒
System.out.println(Thread.currentThread().getName() + " has been notified");
}
public synchronized void notifySignal() {
System.out.println(Thread.currentThread().getName() + " sends signal");
notify(); // 唤醒等待的线程
}
}
public class Main {
public static void main(String[] args) {
WaitDemo waitDemo = new WaitDemo();
Thread thread1 = new Thread(() -> {
try {
waitDemo.waitForSignal();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread 1");
Thread thread2 = new Thread(() -> {
waitDemo.notifySignal();
}, "Thread 2");
thread1.start();
thread2.start();
}
}
```
在上面的示例中,WaitDemo类中的waitForSignal方法会使当前线程进入等待状态,直到其他线程调用notify方法唤醒它。Main类中创建了两个线程,其中一个线程调用waitForSignal方法等待信号,另一个线程调用notifySignal方法发送信号。运行程序后,可以看到线程1进入等待状态,直到线程2调用notifySignal方法唤醒它。