2017-01-22 3 views
2

exampleMethodと呼ばれる方法があります。 私はこのメソッドを呼び出すときに(ネットワークで動作します...)何度か、ネットワークが遅くなると時間がかかります...Javaで何らかのメソッドを実行するための時間を設定する方法は?

実行時間を最大限に設定するにはどうすればよいですか?

たとえば10秒。このよう

...

try { 
     exampleMethod(); 
} catch(Exeption e) { 
     LoggError("I was to slow"); 
} 

私はあなたが、私を理解して任意の助けをありがとう、期待しています。、

+0

どのような方法で処理されているかによって異なります。通常、操作をブロックすると、タイムアウトまたは中断が許可されます。 – shmosel

+0

[スレッドをタイムアウトさせる方法]の複製がありますか(0120-18753)。 – tucuxi

+0

確かに、独自のタイムアウトラッパーを作成できますか?可能です? – rilav

答えて

0

場合は、ExecutorServiceのを使用してタイムアウト値を設定し、将来をキャンセルすることができますスレッドの中断を要求するためにタイムアウトが渡されます。

ExecutorService executorService = Executors.newSingleThreadExecutor(); 
    Future<?> future = null; 
    try { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       while (true) { 
        // it the timeout happens, the thread should be interrupted. Check it to let the thread terminates. 
        if (Thread.currentThread().isInterrupted()) { 
         return; 
        } 
        exampleMethod(); 
       } 

      } 
     }; 

     future = executorService.submit(r); 
     future.get(10, TimeUnit.SECONDS); 
    } 

    // time is passed 
    catch (final TimeoutException e) { 
     System.out.println("I was to slow"); 
     // you cancel the future 
     future.cancel(true); 
    } 
    // other exceptions 
    catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     executorService.shutdown(); 
    } 
} 
+1

それはタスクを停止しません、それは単にそれを待つのを止めるでしょう。 – shmosel

関連する問題