在非阻塞while(true)循环中,wait(1)是否比使用wait()和notify()更有效? [英] Is wait(1) in a non-blocking while(true)-loop more efficient than using wait() and notify()?

查看:344
本文介绍了在非阻塞while(true)循环中,wait(1)是否比使用wait()和notify()更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

wait()notify()的阻塞循环相比,while(true) Java循环与wait(1)一起使用的资源更多还是更少?

Does a while(true) Java loop together with wait(1) use more or less resources than a blocking loop with wait() and notify()?

CPU内核是否具有一些特殊的(硬件)实现方式允许wait(1)?如果是,在使用这种非阻塞循环时是否有任何限制?

And do the CPU cores have some special (hardware) implementations to allow wait(1)? If yes, are there any limitations while working with such non-blocking loops?

一个例子:

while(true){
    wait(1);
    //do the job here...
}

(请注意:如果没有wait(1),一个核将在while(true)循环中100%激进...)

(Just a note: Without the wait(1) a core would go radical 100% in a while(true) loop...)

推荐答案

关于为什么while (true);占用的CPU比while (true) { wait(1); }多的原始问题,请考虑:现代CPU每秒可以执行数十亿条指令.使用wait(1)循环,假设它是完美的,并且每次恰好等待一毫秒,您就将CPU限制为每秒一千条指令.没有它,就没有限制,它可以每秒数十亿次运行紧密循环.

As to the original question of why while (true); takes up more CPU than while (true) { wait(1); }, consider: a modern CPU can perform billions of instructions per second. With the wait(1) loop, assuming it is perfect and waits exactly one millisecond each time, you're limiting the CPU to one thousand instructions per second. Without it, there's no limit and it can run the tight loop billions of times per second instead.

关于哪个新问题更有效,while (true) { wait(1); }方法与wait()相对,并且被notify()编辑...

As to the new question of which is more efficient, the while (true) { wait(1); } approach vs. wait() and being notify()ed...

好吧,假设您正在等待某种状况.选项一:

Well let's say you're waiting on a condition. Option one:

while (true) {
    wait(1);
    if (condition()) {
        break;
    }
}

vs.

wait();

和其他地方:

//code which causes condition() to be true
notify();

说条件为真需要10秒.在第一种方法中,您呼叫wait(1) 10,000次,并检查condition() 10,000次.在第二种方法中,您调用一次wait()notify()一次.

Say it takes 10 seconds for condition to be true. In the first approach, you call wait(1) 10,000 times and check condition() 10,000 times. In the second approach, you call wait() once and notify() once.

这篇关于在非阻塞while(true)循环中,wait(1)是否比使用wait()和notify()更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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