最近在項目中,需要調(diào)用其他APP提供的AIDL接口,項目要求必須執(zhí)行完該操作,才能執(zhí)行后續(xù)的程序,所以必須設置代碼執(zhí)行的超時時間,找到如下代碼可以滿足需求:
public class ThreadTest {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
final ExecutorService exec = Executors.newFixedThreadPool(1);
Callable<String> call = new Callable<String>() {
public String call() throws Exception {
//開始執(zhí)行耗時操作
Thread.sleep(1000 * 2);
return "線程執(zhí)行完成.";
}
};
try {
Future<String> future = exec.submit(call);
String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); //任務處理超時時間設為 1 秒
System.out.println("任務成功返回:" + obj);
} catch (TimeoutException ex) {
System.out.println("處理超時啦....");
ex.printStackTrace();
} catch (Exception e) {
System.out.println("處理失敗.");
e.printStackTrace();
}
// 關(guān)閉線程池
exec.shutdown();
}
}