让线程在 Java 中等待是不是很糟糕? [英] Is it bad to have threads waiting in java?

查看:59
本文介绍了让线程在 Java 中等待是不是很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本上包含的线程

I have a thread that basically contains

while(true) {
  current = BlockingQueue.take();
  results = queryDatabaseWith(current);
  AtomicReference.set( results );
}

实际上,队列中只会放一些东西,但重要的是,当事情发生时,数据库查询以正确的顺序发生.原子引用很好,因为我只关心最后一个数据库查询的结果.

Realistically the queue is only ever going to have a few things put on it, but it's important that when things are, the DB queries happen in the correct order. The atomic ref is fine as I only care about the results from the last DB query.

把这个放在一个线程上是不是很糟糕,基本上一整天都在等待?

Is it bad practice to have this on a thread, basically waiting all day?

推荐答案

不,一般来说,有等待线程也不错,这是常见的做法,也是最好的解决方案.

No it is not bad to have waiting threads in general, it is common practice and often the nicest solution.

由于答案很短,所以只是一个简短的建议:如果您的线程不需要立即做出反应,您可以考虑将 Thread.yield 添加到您的无限等待循环中,这取决于它运行的系统,这可以节省一些不必要的 CPU 使用率.查看 Oracle 文档

As the answer is pretty short, just a quick advice: If it is not necessary that your thread reacts immediately, you might consider adding Thread.yield to your infinite waiting loop, depending on the system it is running on this can save some unnecessary CPU-usage. See the Oracle documentation

这篇关于让线程在 Java 中等待是不是很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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