線程執行設置超時時間

 

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("主程序執行完成……");
    }

}

 

參考https://blog.csdn.net/a9529lty/article/details/42711029

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章