import java.util.concurrent.*;
/**
* 記錄,備忘……
* 線程執行設置超時時間
*/
public class Main2 {
// 定義線程池,推薦手動創建線程池: https://blog.csdn.net/LLLLLiSHI/article/details/88057655
private static ExecutorService pool = Executors.newFixedThreadPool(1);
/**
* jdk的api:Future類已經提供滿足的api
*/
public static void main(String[] args) {
System.out.println("主程序執行開始……");
//定義線程
Callable call = new Callable<String>(){
@Override
public String call() throws Exception {
// 設置2秒睡眠
TimeUnit.SECONDS.sleep(2);
return "這是線程執行結果……";
}
};
// 手動控制線程
Future result = pool.submit(call);
try {
// 如果在超時時間內,沒有數據返回:則拋出TimeoutException異常
Object callResult = result.get(1, TimeUnit.SECONDS);
System.out.println(callResult);
} catch (InterruptedException e) {
System.out.println("InterruptedException發生");
} catch (ExecutionException e) {
System.out.println("ExecutionException發生");
} catch (TimeoutException e) {
System.out.println("TimeoutException發生,意味着線程超時報錯");
}
System.out.println("主程序執行完成……");
}
}