简体   繁体   English

线程在java中等待是不是很糟糕?

[英]Is it bad to have threads waiting in 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. 一般来说,等待线程并不坏,这是常见的做法,通常是最好的解决方案。

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. 由于答案非常简短,只需快速建议: 如果您的线程没有必要立即做出反应 ,您可以考虑将Thread.yield添加到无限等待循环中,具体取决于它运行的系统,可以节省一些不必要的CPU -用法。 See the Oracle documentation 请参阅Oracle文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM