无限线程优化 [英] Indefinite Thread Optimization

查看:40
本文介绍了无限线程优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个无限期运行的线程而没有像 while 这样的昂贵循环?

How anyone can write an Indefinite running Thread without a costly loop like while?

就像我不想要这样的东西

Like I don't want something like this

public void run() {

            while(true)
            {
                do Blah Blah Blah
                Thread.sleep(.....);

            }

        }

编写如此长时间运行的线程的任何优化方法.

Any optimized way to write such a long running thread.

提前致谢.

推荐答案

您认为 while(true) 在哪些方面代价高昂"?您有任何证据表明这会影响您的表现吗?您认为哪种手术比它便宜?

In what way do you consider while(true) "costly"? Do you have any evidence that this is affecting your performance? What operation would you consider to be cheaper than it?

请注意,来自您的评论:

Note that from your comment:

我猜这样一个无限的while循环会阻塞你的CPU.不是达吗?所以我认为它很昂贵.

I guess such a infinite while loop blocks your CPU. Isn't dat? So I consider it costly.

听起来您正在考虑 整个 循环,而不是 while 部分.所以让我们看看你在循环中做了什么:

it sounds like you're considering the whole loop, not the while part. So let's look at what you're doing in the loop:

do Blah Blah Blah
Thread.sleep(.....);

您明确地告诉线程休眠.当它处于睡眠状态时,它不会消耗 CPU 资源.所以不,它并不昂贵.诚然,如果您的睡眠时间很短并且您的do Blah Blah Blah"非常快,那么您将循环很多次——但在这种情况下,您应该考虑增加睡眠时间.(您还应该考虑其他方法,这些方法允许您向线程发出您希望它干净退出的信号,并且即使在它处于睡眠状态时也这样做,而不必中断线程.)

You're explicitly telling the thread to sleep. While it's sleeping, it won't be consuming CPU resources. So no, it's not costly. Admittedly if your sleep period is very short and your "do Blah Blah Blah" is very quickly, you'll be looping an awful lot - but in that case you should consider increasing the sleep time. (You should also consider other approaches which allow you to signal to the thread that you wish it to quit cleanly, and do so even while it's sleeping, without having to interrupt the thread.)

您没有向我们提供有关您真正想要实现的目标的任何信息,但从根本上说,使用 while 在这里不是问题.想想你希望循环的频率,以及它是否真的是一个简单的基于时间的值.例如,如果此线程旨在处理工作,那么您可能需要某种描述的生产者/消费者队列 - 线程在有工作要做时无需休眠,但无需唤醒它直到有工作要做.当然,这只是一个例子 - 如果没有更多信息,我们真的无法提供更多建议.

You haven't given us any information about what you're really trying to achieve, but fundamentally the use of while isn't a problem here. Just think about how often you want to loop, and whether it's really a simple time-based value. For example, if this thread is meant to process work, then perhaps you want a producer/consumer queue of some description - there's no need for the thread to sleep while it has work to do, but there's no need for it to wake up until there's work to do. That's only an example, of course - without more information we really can't give much more advice.

这篇关于无限线程优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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