我正在尝试为我的游戏制作一个简单的消息管理器。但是,出现以下异常:
Exception in thread "main" Exception in thread "Thread-4" java.lang.ClassCastException: MessageManagement.Message cannot be cast to java.lang.Comparable
at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(Unknown Source)
at java.util.concurrent.PriorityBlockingQueue.offer(Unknown Source)
at java.util.concurrent.PriorityBlockingQueue.add(Unknown Source)
at MessageManagement.MessageManager.EnqueueMessage(MessageManager.java:69)
初始化代码为:
MessageManager messageManager = new MessageManager();
messageManager.start();
//send bootstrap message
CJournal.Journal(Main.class, "Testing messanger: ending bootstrapping message to messagemanager");
Message boot_strap_message = new Message();
boot_strap_message.mflag = EEventMachine.EM_BOOTSTRAP;
messageManager.EnqueueMessage(boot_strap_message);
实际的消息管理器是:
public class MessageManager extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
while (true)
{
if (!messagesQueue.isEmpty())
{
//pull message from queue
Message message = messagesQueue.remove();
//dispatch messages according to their type
switch(message.mflag)
{
case EM_BOOTSTRAP:
CJournal.Journal(MessageManager.class, "Messaging system working properly.");
default:
CJournal.Journal(MessageManager.class, "Dispatch Message Trashed");
}
}
}
}
public static PriorityBlockingQueue<Message> messagesQueue = new PriorityBlockingQueue<Message>();
public static void EnqueueMessage(Message message)
{
//Error happens here
messagesQueue.add(message);
}
为什么会出现此错误,我需要怎么做才能解决?
最佳答案
每PriorityBlockingQueue's javadoc
您的Message
类需要实现Comparable
class Message implements Comparable<Message> {
public int compareTo(Message m) {
int comparisonResult = //comparison logic.
return comparisonResult;
}
}
每个Comparable#compareTo的javadoc,
compareTo
您的另一个选择是将Comparator提供给
PriorityBlockingQueue
。