ฉันมีแอพพลิเคชั่นแบบมัลติเธรดที่เธรดส่งข้อความไปยังเธรดอื่น เธรดที่รอจะโพลสำหรับข้อความและโต้ตอบ (จัดการการล็อค) แบบนี้:
รอรหัสเธรด:
while(true)
{
if(helloArrived())
System.out.println("Got hello");
if(byeArrived())
System.out.println("Got bye");
if(stopArrived())
break;
}
ฉันต้องการหลีกเลี่ยงเทคนิคการ hogging 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());
}
}
}