【问题标题】:Java - How to measure a time outJava - 如何测量超时
【发布时间】:2013-04-05 20:16:39
【问题描述】:

我正在使用 Java 套接字制作一个 ping 程序。我的程序中的一个错误是有时它无法连接,并且会永远坐在那里。所以我试图添加一个超时(二十秒后),ping 将失败。但我不知道该怎么做。

这是我的 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 块开始或我的代码中的其他任何地方已经过去了 20 秒,以便它不会在 ping 期间卡住的任何建议?

【问题讨论】:

  • 线程框架为此提供了非常好的工具。
  • 你可以在一个单独的线程中执行你的 ping 并使用Thread.join() 给它一些时间来完成。
  • @jahroy - Ummmm...你能给我举个例子吗?
  • 我现在有点忙,但这里是 Oracle 教程中的 one simple example

标签: java time timer


【解决方案1】:

正如“jsn”和“jahory”所说,您需要使用线程来执行此操作。这里有 2 个有用的链接,您可以查看它们;)

【讨论】:

  • 我看到了一个线程的行为,它把所有东西都卡住了,直到它完成。这会做同样的事情吗?
  • 线程的意义在于你的程序可以在线程并行工作的同时继续执行......所以线程应该在“一切都卡住的情况下提供解决方案"。
【解决方案2】:

您可以使用FutureFutureTask

   ExecutorService pingExecutor = ... // executor service to run the ping in other thread

   void showPing(final String target) throws InterruptedException {

     Future<String> ping = executor.submit(new Callable<String>() {
         public String call() {
             String pingResult = ... // do your Ping stuff
             return pingResult;
         }});

     System.out.println("Pinging..."); // do other things while searching

     try {
       System.out.println(future.get(20, TimeUnit.SECONDS)); // use future, waits 20 seconds for the task to complete
     } catch (ExecutionException ex) {
     } catch (TimeoutException tex) {
       // Ping timed out
     }
   }

【讨论】:

    【解决方案3】:

    你可以在这里找到一些提示:How do I call some blocking method with a timeout in Java?

    未来的界面看起来可以很好地解决您的问题。但是请记住,根据您的任务正在做什么,您可能无法真正取消它。附加信息:

    【讨论】:

    • 只有链接的答案不好 - 链接可能会随着时间的推移而中断。
    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2011-02-16
    • 2011-04-04
    相关资源
    最近更新 更多