错误的线程等待

时间:2017-08-18 20:22:30

标签: java multithreading sockets wait

我试图从套接字读取数据,但是这个线程不是唯一的线程读取。第二个线程侦听正在发送的命令。我想要做的是让侦听命令的线程等到我在第二个线程上完成。 问题是命令监听线程没有等待,而是我想要监听的其他线程等待。

这是由我不想等待的线程运行的方法

public void sendMessage(Message message) {
   pauseListener(true);
   try {
   //Inform the receiver that a message is to be sent
      System.out.println("Sending message");
   sendFunction(Function.SND_MESSAGE);
   //And wait for a response, OK will allow for sending of data
   System.out.println("Awaiting confirmation");
   Error status = readError();
   if(status == Error.OK) {
      System.out.println("Sending message data");
      //Send the data
      sendBytes(message.getSender().getBytes(), 0);
      byte[] byteLong = Long.toString(message.getID()).getBytes();
      sendBytes(byteLong, 0);
      sendBytes(message.getData().getBytes(), 0);
      sendError(Error.OK);
   } else {
      //TODO error handling
      System.err.println("Failed to send message: " + status.name());
   }
   } catch (Exception e) {
      //TODO Error stuff
      System.err.println("An error occured sending message");
      e.printStackTrace();
   } finally {
      pauseListener(false);
  }

}

方法暂停监听器意味着使监听等待,我对使用线程非常陌生,所以任何建议都会受到赞赏。 self.wait()设置为我想要等待的线程的实例

public void pauseListener(boolean pause) {
   synchronized (self) {
      try {
         if(pause) {
            self.wait();
         } else {
            self.notify();
         }
      }catch(InterruptedException e) {
         System.err.println("Failed to suspend listener on client:" + socket);
         e.printStackTrace();
      }
  }

}

这是我试图等待的线程的run()。

public void run() {
   //Listen for commands
   self = Thread.currentThread();
   while(true) {
   System.out.println("Awaiting instruction");
   Function function;
   try {
      function = readFunction();
   } catch (UnkownCommandException e) {
      e.printUserFriendly();
      e.printStackTrace();
      continue; //Skip the unknown function
   }

   switch (function) {
     case SND_MESSAGE: //Prepare to receive a message
        System.out.println("Receiving message");
        Message input = readMessage();
        if(server != null) {
           server.broadCast(input);
        } else {
           System.out.println(input.toString());
        }

        break;

     default:
        System.out.println("Unknown function: " + function.name());
        break;
     }
   }
}

如果您需要更多信息,我可以提供。任何帮助将不胜感激,可以用一双新鲜的眼睛。

0 个答案:

没有答案
相关问题