我正在使用Java套接字進行ping程序。我的程序中的一個錯誤是,有時它不會連接,只會永遠坐在那裏。所以我試圖添加一個超時(二十秒後),ping會失敗。但我不知道如何。Java - 如何測量超時
這裏是我的ping程序的一部分:
boolean result = false;
long before1 = System.nanoTime();
out.println(new byte[64]);
System.out.println("(1) Sent 64 bytes of data to " + address
+ "...");
try {
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
long after = System.nanoTime();
long s = ((after - before1)/1000000L)/1000;
System.out.println("(1) Recieved reply from " + address
+ " (" + size + " bytes), time = " + s
+ " seconds...");
result = true;
} else if ((in.readLine()) == null) {
long after = System.nanoTime();
long s = ((after - before1)/1000000L)/1000;
System.out.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...");
result = false;
}
} catch (IOException exc) {
long after = System.nanoTime();
long s = ((after - before1)/1000000L)/1000;
System.err.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...\nReason: "
+ exc);
result = false;
}
但我想測量時間在我的代碼經過的任何地方,而不是:
long time = System.nanoTime();
如果我的代碼的一部分是停滯不前,20秒後會超時。
關於如何在try/catch塊的開始處或者代碼中的其他地方測量二十秒鐘的任何建議,以便在ping過程中不會卡住?
線程框架有這個非常好的設施。 – jn1kk 2013-04-05 20:20:53
您可以在單獨的線程中執行ping命令並使用[Thread.join()](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join(long) )給它一些時間來完成。 – jahroy 2013-04-05 20:21:02
@jahroy - 嗯...你能告訴我一個例子嗎? – 0101011 2013-04-05 20:29:27