[英]How to execute a blocking function that returns a value for a maximum amount of time in Java
我將如何制作一個可以在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);
這是我在類似情況下所做的
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");
}
如果ReceiveData正在與網絡通信,則只需對其設置讀取超時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.