// Java线程等待示例代码
class WaitNotifyExample {
private final Object lock = new Object();
private boolean isProduced = false;
public void producer() throws InterruptedException {
synchronized (lock) {
System.out.println("Producer thread running...");
while (isProduced) {
System.out.println("Waiting for consumer to consume...");
lock.wait(); // 线程等待,直到被唤醒
}
// 生产者生产数据
System.out.println("Producing...");
isProduced = true;
lock.notify(); // 唤醒等待的线程
System.out.println("Notifying consumer...");
}
}
public void consumer() throws InterruptedException {
synchronized (lock) {
System.out.println("Consumer thread running...");
while (!isProduced) {
System.out.println("Waiting for producer to produce...");
lock.wait(); // 线程等待,直到被唤醒
}
// 消费者消费数据
System.out.println("Consuming...");
isProduced = false;
lock.notify(); // 唤醒等待的线程
System.out.println("Notifying producer...");
}
}
public static void main(String[] args) {
WaitNotifyExample example = new WaitNotifyExample();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
example.producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
example.consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
private final Object lock = new Object();
创建一个锁对象,用于同步控制。producer()
方法中,使用 synchronized
关键字确保同一时刻只有一个线程可以访问临界区。如果 isProduced
为 true
,表示已经有数据被生产,生产者线程调用 lock.wait()
进入等待状态,直到被消费者线程唤醒。生产完成后调用 lock.notify()
唤醒消费者线程。consumer()
方法逻辑与生产者类似,只是它在没有数据时进入等待状态,并在消费完数据后唤醒生产者线程。通过这种方式,生产者和消费者线程可以通过 wait()
和 notify()
方法进行协作,确保数据的正确生产和消费。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站