等待变量更改其值的最佳方法 [英] Best way to wait until a variable changes its value

查看:50
本文介绍了等待变量更改其值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到我要问的不是特定的Codename One问题,而是通用的Java问题,无论如何,考虑到参考API是Codename One的问题,是否有一种更优雅,更可靠的方式来处理情况像下面的代码?如果我需要同步制作本质上与回调异步的代码,则会发生这种情况:

I realize that what I'm about to ask is more a generic Java question than a specific Codename One question, anyway, considering that the reference APIs are Codename One's, is there a more elegant and more reliable way to handle a situation like the following code? Such cases happen if I need to synchronously make code that by its nature would be asynchronous with callback:

while (lock) {
   CN.invokeAndBlock(() -> Util.sleep(500));
}

我在这里引用了这样的代码: https://github.com/codenameone/CodenameOne/issues/3192

I quoted a code like that here: https://github.com/codenameone/CodenameOne/issues/3192

推荐答案

JavaSE具有一些很酷的功能,但我们目前不支持它们,例如 CountDownLatch .

JavaSE has some pretty cool features to do that but we don't support them at this time e.g. CountDownLatch.

但这仍然很容易做到:

public class SharedVar<T> {
    private T var;
    public T get() { return var; }
    public synchronized void set(T var) {
       this.var = var;
       notifyAll();
    }
    public synchronized T waitForChange() {
       wait();
       return var;
    }
}

这篇关于等待变量更改其值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆