Best way to wait until a variable changes its value

我怕爱的太早我们不能终老 提交于 2021-02-08 04:46:24

问题


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));
}

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


回答1:


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

But this is still pretty easy to do:

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;
    }
}


来源:https://stackoverflow.com/questions/63385557/best-way-to-wait-until-a-variable-changes-its-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!