在 Java 中,可以使用 Condition 接口来等待一个变量值的变化。Condition 接口是 Java 中 Lock 的一部分,用于线程间的协调和通信。

下面是一个简单的示例代码,演示如何使用 Condition 等待一个变量值的变化:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class VariableConditionExample {
    private int variable = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void waitForValue(int value) throws InterruptedException {
        lock.lock();
        try {
            while (variable != value) {
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }

    public void changeValue(int value) {
        lock.lock();
        try {
            variable = value;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

在上面的例子中,我们定义了一个变量'variable',并使用 ReentrantLock 创建了一个锁对象'lock',以及一个 Condition 对象'condition'。

'waitForValue'方法会等待'variable'的值变为指定的'value'。在方法中,首先获取锁,然后使用 while 循环来判断'variable'的值是否等于'value',如果不等于,则调用'condition.await()'方法来使线程等待。当'variable'的值变为'value'时,调用'condition.signalAll()'方法来唤醒等待的线程。

'changeValue'方法用于改变'variable'的值,并通过'condition.signalAll()'方法唤醒等待的线程。

可以在多个线程中使用'VariableConditionExample'对象来演示等待变量值变化的效果。例如:

public class Main {
    public static void main(String[] args) {
        VariableConditionExample example = new VariableConditionExample();

        Thread thread1 = new Thread(() -> {
            try {
                example.waitForValue(5);
                System.out.println('Thread 1: Variable value changed to 5');
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(1000); // Let thread1 wait for value first
                example.changeValue(5);
                System.out.println('Thread 2: Variable value changed to 5');
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();
    }
}

在上面的例子中,我们创建了两个线程,其中一个线程调用'waitForValue'方法等待'variable'的值变为 5,另一个线程调用'changeValue'方法将'variable'的值改为 5。

运行以上代码,可以看到输出结果为:

Thread 1: Variable value changed to 5
Thread 2: Variable value changed to 5

这表明线程 1 成功等待到了变量值的变化,并被唤醒。

Java 使用 Condition 等待变量值变化

原文地址: https://www.cveoy.top/t/topic/pWvq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录