问题描述
对于此学校作业,我需要使用Java线程(无需套接字等)来模拟客户端服务器类型的应用程序.我该怎么做呢?
For this school assignment, I need to simulate a client server type application using Java threads (no need for sockets etc). How might I go about doing it?
我需要一种启动服务器并等待客户端调用它的方法,然后它应该返回响应.我脑海中的"API"类似于:
I need a way to server to start and wait for clients to call it then it should return a response. The "API" in my mind was something like:
server.start()
client1.connect(server)
client2.connect(server)
x = client1.getData()
y = client2.getData()
success1 = client1.sendData(1)
success2 = client2.sendData(2)
server | client.run方法的外观如何?假设我现在可以对方法调用进行硬编码.
How might the server|client.run method look like? Assume I could hardcode the method calls for now.
推荐答案
我建议使用以下方法:
1.具有与阻塞队列"配合使用的服务器"代码-
阻塞队列是一种已同步的数据结构,让我们从中读取数据的线程(消费者"线程)等待,直到队列中有待读取的数据为止.
生产者"线程是在队列中推送"数据的线程.
我建议您使用阻止队列之一实现.
我还建议您阅读有关消费者生产者"模式的更多信息.
阻塞队列还消除了在多线程编程中不建议的忙等待".
I suggest to use the following approach:
1. Have "server" code that works with Blocking Queue -
A blocking queue is a data structure which is synchronized and let's the thread that reads data from it (the "consumer" thread) to wait until there is a data in the queue to be read.
The "producer" thread is a thread that "pushes" data on the queue.
I would recommend you use one of the blocking queue implementations.
I would also suggest you read more about "consumer producer" pattern.
Blocking queue also eliminates the need for "busy wait" which is not recommended in multi-threading programming.
这篇关于如何使用Java线程模拟客户端服务器应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!