触发暂停并在方法中继续?

时间:2022-11-03 21:36:17

How could I "pause" a method in between an execution, and trigger it externally to continue the execution of this method?

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

The Thread is a servlet, and the executeAndWait method is started by a button click. Now I want to do polling on a SessionScoped variable. If this variable changes its state (eg to true), the polling/waiting method should continue.

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

I first though about Observer pattern. But with this I can just trigger the execution of methods. But I need to sleep/wait and trigger the continue of a method.

我首先谈论Observer模式。但有了这个,我就可以触发方法的执行。但我需要睡眠/等待并触发方法的继续。

How else could this be done apart from polling to a "global" variable.?

除了轮询到“全局”变量之外,还能做些什么?

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

1 个解决方案

#1


0  

You could use a CountDownLatch.

您可以使用CountDownLatch。

Initialize it to 1, call await() in MyThread, and then call the countDown() method from MySignal when it should be released.

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

This way you don't need to keep polling the value of a variable.

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

#1


0  

You could use a CountDownLatch.

您可以使用CountDownLatch。

Initialize it to 1, call await() in MyThread, and then call the countDown() method from MySignal when it should be released.

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

This way you don't need to keep polling the value of a variable.

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