2014-01-28 41 views
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类将收到一条消息,其中包括向量时钟。我的问题变成了,将此消息传回我的主线程(即处理内部事件和发送事件的消息)的最佳方式是什么?我的主线是我有矢量时钟的地方,并执行我所有的操作。

+1

我不确定我是否理解你的执行路径,但看看BlockingQueue,ScheduledExecutorService和Future。 –

+0

记得接受我的答案,如果它帮助你。谢谢。 – Gray

回答

0

我的问题变成,这将是得到这个消息,回到我的主线程

你可能会考虑切换到使用ExecutorService的最佳方式。然后你可以提交一个Callable,你可以很容易地将结果返回到主线程。

// this is for 1 thread but you can also use a fixed number of threads or dynamic 
ExecutorService threadPool = Executors.newSingleThreadExecutor(); 
Future<SomeResult> future = threadPool.submit(new Callable<SomeResult>() { 
    public SomeResult call() { 
     // thread code goes here 
    } 
}); 
// after you submit the last job, you can shutdown the pool 
threadPool.shutdown(); 
... 
// later you can get the result 
SomeResult result = future.get();