我正在开发一个 Java 客户端/服务器应用程序,对于如何开发它有一套非常具体的规则。服务器创建 ClientHandler
具有到客户端套接字的输入和输出流的实例,它们之间的任何输入和输出都由客户端 GUI 中的事件触发。
我现在添加了服务器端功能,该功能将定期向所有连接的客户端发送更新(通过将 PrintWriter
中创建的每个 ClientHandlers
对象存储在 ArrayList<PrintWriter>
中来完成)。我需要一个等效的客户端机制来处理这些消息,并且被告知这需要在第二个客户端线程中发生,其 run()
方法使用 do...while(true)
循环直到客户端断开连接。
假设来自服务器的每条消息都发送 boolean
值(value)true
向所有人发送消息,以及值 false
之一给个别客户的消息...
Existing Client Thread
//method called from actionPerformed(ActionEvent e)
//handles server response to bid request
public void receiveResponse()
{
//thread should only process to-specific-client messages
if (networkInput.nextBoolean() == false)
{
//process server response...
}
}
Second Client-side Thread
//should handle all messages set to all clients
run()
{
do {
if (networkInput.nextBoolean() == true)
{
//process broadcasted message...
} while (true);
}
由于他们需要使用相同的输入流,我显然会添加一些 synchronized
, wait/notify
打电话,但一般来说,我想在这里做的事情可能吗?或者尝试从同一输入流读入的两个线程是否会互相干扰太多?
请告诉我你的想法!
谢谢, 标记
最佳答案
你可以做到,尽管测试和正确执行会很复杂。多少是“太多”取决于你。一个更简单的解决方案是让读取器线程将消息传递给两个工作线程。
ExecutorService thread1 = Executors.newSingleThreadedExecutors();
ExecutorService thread2 = Executors.newSingleThreadedExecutors();
while(running) {
Message message = input.readMessage();
if (message.isTypeOne())
thread1.submit(() -> process(message));
else if (message.isTypeTwo())
thread2.submit(() -> process(message));
else
// do something else.
}
thread1.shutdown();
thread2.shutdown();
关于Java - 客户端的两个线程可以使用来自服务器的相同输入流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188336/