【问题标题】:Trigger pause and continue within a method?在方法中触发暂停和继续?
【发布时间】:2012-08-22 21:16:50
【问题描述】:

如何在执行之间“暂停”一个方法,并在外部触发它以继续执行该方法?

线程是一个servlet,executeAndWait 方法是通过单击按钮启动的。 现在我想对 SessionScoped 变量进行轮询。 如果此变量更改其状态(例如变为 true),则轮询/等待方法应继续。

我首先想到的是Observer 模式。但是有了这个我可以触发方法的执行。但我需要休眠/等待并触发方法的继续

除了轮询“全局”变量之外,还能如何做到这一点?

class MyThread {

    @Inject
    MyBean bean;

    doExecuteAndWait() {
        //this waits for the var to turn into "true" state
        while(!bean.isVarValid()) {
            Thread.sleep(1000);
        }
        //continue execution if somevar is set to true externally
    }
}


class MySignal {
    @Inject
    MyBean bean;

    //this triggers the continuation of the method from class above
    toggleVar() {
        bean.setVarValid(true);
    }   
}

@SessionScoped
class MyBean() {
    varValid = false;

    isVarValid() {
        return varValid;
    }

    setVarValid(Boolean status) {
        this.varValid = status;
    }
}

【问题讨论】:

    标签: java jsf jakarta-ee servlets


    【解决方案1】:

    您可以使用CountDownLatch

    初始化为1,在MyThread中调用await(),然后在应该释放的时候从MySignal调用countDown()方法。

    这样你就不需要一直轮询变量的值了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      相关资源
      最近更新 更多