在java中有一个'阻止直到条件变为真'的功能吗? [英] is there a 'block until condition becomes true' function in java?

查看:266
本文介绍了在java中有一个'阻止直到条件变为真'的功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为服务器编写一个监听器线程,目前我正在使用:

I'm writing a listener thread for a server, and at the moment I'm using:

while (true){
    try {
        if (condition){
            //do something
            condition=false;
        }
        sleep(1000);

    } catch (InterruptedException ex){
        Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

使用上面的代码,我遇到了问题用run函数吃掉所有cpu时间循环。睡眠功能有效,但它似乎是一个临时修复,而不是解决方案。

With the code above, I'm running into issues with the run function eating all the cpu time looping. The sleep function works, but it seems be a makeshift fix, not a solution.

是否有某些功能会阻塞,直到变量'condition'变为'true'?
或者是否继续循环等待变量值变化的标准方法?

Is there some function which would block until the variable 'condition' became 'true'? Or is continual looping the standard method of waiting until a variable's value changes?

推荐答案

这样的轮询肯定是最不喜欢的解决方案。

Polling like this is definitely the least preferred solution.

我假设您有另一个线程可以使条件成立。有几种方法可以同步线程。在你的情况下最容易的是通过对象的通知:

I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:

主线程:

synchronized(syncObject) {
    try {
        // Calling wait() will block this thread until another thread
        // calls notify() on the object.
        syncObject.wait();
    } catch (InterruptedException e) {
        // Happens if someone interrupts your thread.
    }
}

其他主题:

// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
    syncObject.notify();
}

syncObject 本身可以是一个简单的对象

syncObject itself can be a simple Object.

还有许多其他的线程间通信方式,但使用哪种方法取决于你究竟在做什么。

There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.

这篇关于在java中有一个'阻止直到条件变为真'的功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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