2017-04-10 58 views
0

我目前正在编写一个小型的Java程序,我有一个客户端向服务器发送命令。一个单独的线程正在处理来自该服务器的回复(回复通常非常快)。理想情况下,我暂停发出服务器请求的线程,直到收到回复或超出某个时间限制时为止。如何使线程等待服务器响应

我目前的解决办法是这样的:

public void waitForResponse(){ 
    thisThread = Thread.currentThread(); 
    try { 
     thisThread.sleep(10000); 
     //This should not happen. 
     System.exit(1); 
    } 
    catch (InterruptedException e){ 
     //continue with the main programm 
    } 
} 

public void notifyOKCommandReceived() { 
    if(thisThread != null){ 
     thisThread.interrupt(); 
    } 
} 

的主要问题是:此代码抛出时一切都会好起来,因为它应该和终止时,坏事发生异常。什么是解决这个问题的好方法?

+0

几种解决方案,在这个线程可用:http://stackoverflow.com/questions/289434/如何让一个Java线程等待另一个线程输出?rq = 1 –

+2

如果发送消息的线程需要等待响应,为什么要等待另一个线程上的响应?无论如何,你必须在同一个线程中进行操作。如果线程仅用于睡眠,则线程无用。无论如何,它抛出了什么异常? – RealSkeptic

+0

它大致上与[如何在Java中异步执行POST REST调用]相同(http://stackoverflow.com/questions/43268903/how-to-make-a-post-rest-call-asynchronously -in-java的)。用远程呼叫替换HTTP部分。 – andih

回答

3

有多个并发基元允许您实现线程通信。您可以使用CountDownLatch来实现类似的结果:

public void waitForResponse() { 
    boolean result = latch.await(10, TimeUnit.SECONDS); 
    // check result and react correspondingly 
} 

public void notifyOKCommandReceived() { 
    latch.countDown(); 
} 

初始化锁存器发送请求如下之前:

latch = new CountDownLatch(1); 
+0

的例子。谢谢,这完美的诀窍。 – Heijne