0
因此,我正在创建一个实现向量时钟算法的简单应用程序。该应用程序做了三件事。 1.它可以做一个内部事件(在我的情况,我选择了这是一些简单的代数) 2.发送消息(跨Socket连接) 3.接收信息(通过ServerSocket的)如何从后台服务器线程获取返回值
后任何这些事件都会发生,您必须更新您自己的本地矢量时钟。但是当你收到一条消息时,发送者的时钟被附加到消息的尾部,你现在必须根据接收到的时钟对你自己的本地时钟做一些更新()。
我这样做的方式是首先启动一个接受传入连接的服务器线程。每个传入的连接然后在服务器线程内创建它自己的线程。我的代码是:
new Thread() { //This thread is the server handler that will accept new clients for communication
public void run(){
try{
ServerSocket server = new ServerSocket(port); //Created a new server for clients (other users) to connect to
while (true) {
ConnectionWorker cw = new ConnectionWorker(server.accept()); //Accept the new client
Thread t = new Thread(cw); //Start the client thread
t.start(); //Start the thread
}
}
catch(Exception e){
e.printStackTrace();
}
}
{
start();
}
};
所以,现在,我的ConnectionWorker类将收到一条消息,其中包括向量时钟。我的问题变成了,将此消息传回我的主线程(即处理内部事件和发送事件的消息)的最佳方式是什么?我的主线是我有矢量时钟的地方,并执行我所有的操作。
我不确定我是否理解你的执行路径,但看看BlockingQueue,ScheduledExecutorService和Future。 –
记得接受我的答案,如果它帮助你。谢谢。 – Gray