我被这段代码困住了,我认为我错过了一些非常重要的东西。当线程运行时,我可以向向量添加消息,但是当它调用通知时,似乎getNextMessageFromQueue()
保持等待。
我是否锁定了消息变量?
谢谢你的帮助。
我的调度程序类将所有消息发送给我的客户:
private Vector<Message> messages = new Vector<Message>();
public synchronized void addMessage(Message message) {
messages.add(message);
notify();
}
private synchronized Message getNextMessageFromQueue() throws InterruptedException {
while (messages.size() < 1) {
wait();
}
Message message = (Message) messages.get(0);
messages.removeElementAt(0);
return message;
}
private void sendMessageToAllClients(Message message) {
for (int i=0; i < clients.size(); i++) {
Client client = (Client) clients.get(i);
client.sendMessage(message);
}
}
public void run() {
try {
while (true) {
Message message = getNextMessageFromQueue();
sendMessageToAllClients(message);
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
这里是客户端类:
private Socket socket;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client(Socket s) throws IOException {
socket = s;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}
public Socket getSocket() {
return socket;
}
public void sendMessage(Message message) {
try {
out.writeObject(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
这是 的主要调用addMessage
:
Message message = new Message();
message.setMessage("Welcome to " + client.getSocket().getLocalAddress() + ":" + client.getSocket().getPort());
dispatcher.addMessage(message);