我想在我的程序做其他事情时监听服务器,当从服务器接收到一条消息时,我想解释它。
我知道线程,但不确定它是如何工作的。如果我有一个线程监听服务器,我如何将该数据传递给主线程进行解释?主线程向服务器发送数据的最佳方式是什么?同步修饰符有什么用?
最佳答案
If I have a thread listening for the server how can I pass that data to the main thread for interpretation? What is the best way for the main thread to send data to the server?
我会使用 BlockingQueue
为了这。您定义单个 BlockingQueue
例如 LinkedBlockingQueue
.然后你的监听器类调用 queue.take()
等待你的服务器调用 queue.put()
。它将所有同步、等待、通知等工作留给 Java 类,而不是您自己的代码。
What is the use of the synchronized modifier?
我会做一些阅读以了解更多关于这一点的信息。这不是可以用简短的 SO 响应来回答的事情。 Java concurrency tutorial是一个很好的起点。
关于java - 在线程之间传递信息的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14148422/