在Java中,wait()
和notify()
方法是Object
类的成员方法,主要用于多线程编程中的线程间通信。wait()
方法会使当前线程等待,直到其他线程调用同一对象的notify()
方法。notify()
方法会唤醒在该对象监视器上等待的单个线程。这两个方法必须在一个同步代码块或同步方法中使用,以确保线程安全。
以下是一个简单的示例,说明如何使用wait()
和notify()
方法:
public class SharedResource {
private boolean resourceAvailable = false;
public synchronized void waitForResource() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " is waiting for the resource.");
wait(); // 当前线程等待,直到资源可用
System.out.println(Thread.currentThread().getName() + " has acquired the resource.");
}
public synchronized void releaseResource() {
System.out.println(Thread.currentThread().getName() + " is releasing the resource.");
resourceAvailable = true;
notify(); // 唤醒等待资源的线程
}
}
public class WorkerThread extends Thread {
private SharedResource sharedResource;
public WorkerThread(SharedResource sharedResource) {
this.sharedResource = sharedResource;
}
@Override
public void run() {
try {
sharedResource.waitForResource();
// 在此处执行使用资源的操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
WorkerThread workerThread1 = new WorkerThread(sharedResource);
WorkerThread workerThread2 = new WorkerThread(sharedResource);
workerThread1.start();
workerThread2.start();
try {
Thread.sleep(2000); // 等待一段时间,以便两个线程都能启动并尝试获取资源
} catch (InterruptedException e) {
e.printStackTrace();
}
sharedResource.releaseResource();
}
}
在这个示例中,我们有一个名为SharedResource
的类,它包含一个布尔变量resourceAvailable
。waitForResource()
方法用于等待资源可用,而releaseResource()
方法用于释放资源。当releaseResource()
被调用时,它会唤醒一个正在等待资源的线程。
WorkerThread
类是一个继承自Thread
的类,它实现了run()
方法。在run()
方法中,我们调用waitForResource()
方法来等待资源。
在main()
方法中,我们创建了两个WorkerThread
实例,并启动它们。然后,我们让主线程休眠一段时间,以便两个工作线程都能启动并尝试获取资源。最后,我们调用releaseResource()
方法来释放资源,唤醒一个等待的线程。