notify方法如何使用
时间: 2023-09-07 16:11:30 浏览: 44
notify() 方法需要在 synchronized 块或方法中调用,因为它需要获取该对象的锁并操作等待队列。下面是一个简单的示例代码:
``` java
public class MyThread implements Runnable {
private Object lock;
public MyThread(Object lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
System.out.println("Thread A: Start");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread A: End");
}
}
}
public class Main {
public static void main(String[] args) {
Object lock = new Object();
Thread threadA = new Thread(new MyThread(lock));
threadA.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
lock.notify();
}
}
}
```
在上述代码中,MyThread 类的 run() 方法中调用了 lock.wait() 方法,使该线程进入等待状态。Main 类中的 synchronized 块调用了 lock.notify() 方法,唤醒了在 lock 对象上等待的线程。需要注意的是,notify() 方法必须在 synchronized 块或方法中调用,并且在调用 notify() 方法后,当前线程仍然持有该对象的锁。