【发布时间】:2014-12-20 00:07:14
【问题描述】:
我有一个多线程应用程序,其中一个线程将消息发送到另一个线程。等待线程轮询消息并做出反应(处理锁)。像这样:
等待线程代码:
while(true)
{
if(helloArrived())
System.out.println("Got hello");
if(byeArrived())
System.out.println("Got bye");
if(stopArrived())
break;
}
我想避免这种占用 CPU 的技术并改用其他方法。有什么想法吗?
编辑:实际代码如下:
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());
}
}
}
【问题讨论】:
-
生产者消费者问题。你试过你的朋友谷歌吗?
-
你需要一个消息队列。您可以使用 BlockingQueue,因此等待线程将被阻塞,直到消息到达。
-
我实际上正在使用该数据结构。但我正在检查函数的大小并将其清除为句柄。有错吗?
-
@Josh 在您使用队列的位置显示您的代码。
标签: java multithreading mutex