如何避免在Java中忙于旋转

如何避免在Java中忙于旋转

本文介绍了如何避免在Java中忙于旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程应用程序,其中一个线程将消息发送到另一个线程。等待线程轮询消息并做出反应(处理锁定)。像这样:

I have a multi-threaded application where a thread sends a message to another thread. The waiting thread polls for the message and reacts (locks are handled). Like this:

等待线程代码:

while(true)
{
  if(helloArrived())
    System.out.println("Got hello");
  if(byeArrived())
    System.out.println("Got bye");
  if(stopArrived())
    break;
}

我想避免这种cpu占用技术并使用别的东西。有什么想法?

I want to avoid this cpu hogging technique and use something else instead. Any ideas?

编辑:实际代码如下:

BlockingQueue<Mail> killMeMailbox = new LinkedBlockingQueue<Mail>();
BlockingQueue<Mail> messageMailbox = new LinkedBlockingQueue<Mail>();

public void run()
    {
        while(true)
        {
            if(killMeMailbox.size() > 0)
            {
                break;
            }
            if(messageMailbox.size() > 0)
            {
              System.out.println(messageMailbox.poll());
            }
        }
     }

public void receiveMail(Mail mail)
    {
        //kill
        if(mail.from == -1)
        {
            killMeMailbox.add(0);
        }
        else
        {
            //other
            try
            {
                messageMailbox.put(mail);
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
    }


推荐答案

避免这种情况的正确方法是使用由 java.lang.Object 实现的等待/通知机制,或者由...提供的更高级别的并发机制之一。 Java类库:

The correct way to avoid this is to use the wait/notify mechanism implemented by java.lang.Object, or one of the higher level concurrency mechanisms provided by the Java class libraries:



  • / ,

  • 阻塞队列;例如实现界面。

  • semaphores,
  • latches / cyclic barriers,
  • blocking queues; e.g. the classes that implemented the BlockingQueue interface.

(选择与您的具体内容最匹配的机制用例...)

(Pick the mechanism that is the best match for what your specific use-case ...)

使用 Thread.sleep 不是一个好的解决方案。当您减少CPU负载时(与轮询循环相比),另一方面是您降低响应速度。

Using Thread.sleep is not a good solution. While you reduce CPU load (compared with a polling loop), the flip-side is that you reduce responsiveness.

是的。您正在以一种旨在避免阻止的方式使用队列。这是错误的做法。您应该使用 take()(这将阻止直到条目可用)而不是 poll(),并获取摆脱测试队列大小的代码。

Yea. You are using the queue in a way that is designed to avoid blocking. That's the wrong approach. You should use take() (which will block until an entry becomes available) instead of poll(), and get rid of the code that tests the queue size.

你的killMeMailbox东西似乎旨在让你停止等待邮件。您应该能够使用 Thread.interrupt 实现它。 (中断将解锁 take()调用...)

Your "killMeMailbox" stuff seems to be designed to allow you to stop waiting for mail. You should be able to implement that using Thread.interrupt. (An interrupt will unblock a take() call ...)

这篇关于如何避免在Java中忙于旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:30