java中是否有“阻塞直到条件变为真"的功能? [英] is there a 'block until condition becomes true' function in java?

查看:17
本文介绍了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 时间循环的问题.sleep 功能有效,但它似乎是临时修复,而不是解决方案.

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.

是否有一些函数会阻塞直到变量条件"变为真"?还是持续循环等待变量值改变的标准方法?

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 本身可以是一个简单的Object.

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天全站免登陆