0

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

Thread 是一个 servlet,该executeAndWait方法通过单击按钮启动。现在我想对SessionScoped变量进行轮询。如果这个变量改变了它的状态(例如变为真),轮询/等待方法应该继续。

我首先考虑的是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;
    }
}
4

1 回答 1

0

您可以使用CountDownLatch

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

这样您就不需要继续轮询变量的值。

于 2012-08-22T21:34:34.453 回答