如何执行一个阻塞函数,该函数在Java中返回最长时间的值

时间:2010-04-28 00:17:30

标签: java multithreading

我将如何制作一个能在java中执行此操作的函数。

String result = null

do
{
  SendData()

  // Run Blocking Function: ReceiveData() Until it returns a result
  // or t seconds have elapsed

  // if something returned, result = something
  // else result = null

} while(result == null);

2 个答案:

答案 0 :(得分:3)

这就是我在类似情况下所做的事情,

private static final ExecutorService THREADPOOL
       = Executors.newCachedThreadPool();

private static <T> T call(Callable<T> c, long timeout, TimeUnit
timeUnit)
       throws InterruptedException, ExecutionException, TimeoutException
   {
       FutureTask<T> t = new FutureTask<T>(c);
       THREADPOOL.execute(t);
       return t.get(timeout, timeUnit);
   }

   try {
       String task = call(new Callable<String>() {
           public String call() throws Exception
           {
              String result = null
              do {
                  SendData()
              } while(result == null);          
            }, 2, TimeUnit.SECONDS);
   } catch (TimeoutException e) {
       System.err.println("Job timedout");
   }

答案 1 :(得分:0)

如果ReceiveData正在与网络通信,只需在其上设置读取超时。