使用Java實現異步調用三方服務超時設置

直接上代碼:

private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * @param args
     */
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String result = timeoutMethod(5000);
        System.out.println("方法實際耗時:" + (System.currentTimeMillis() - start) + "毫秒");
        System.out.println("結果:" + result);
        try {
            Thread.sleep(8000);
            long start1 = System.currentTimeMillis();
            String result1 = timeoutMethod(5000);
            System.out.println("方法實際耗時:" + (System.currentTimeMillis() - start1) + "毫秒");
            System.out.println("結果:" + result1);
        } catch (Exception e) {

        }
    }

    private static String timeoutMethod(int timeout) {
        String result = "超時標誌";
        FutureTask<String> futureTask = new FutureTask<>(() -> unknowMethod());
        executorService.execute(futureTask);
        try {
            result = futureTask.get(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            futureTask.cancel(true);
            result = "超時標誌";
        }
        return result;
    }

    private static String unknowMethod() {
        Random random = new Random();
        int time = (random.nextInt(10) + 1) * 1000;
        System.out.println("任務將耗時: " + time + "毫秒");
        try {
            Thread.sleep(time);
        } catch (Exception e) {

        }
        return "真實結果";
    }

運行結果1:

任務將耗時: 2000毫秒
方法實際耗時:2044毫秒
結果:真實結果
任務將耗時: 4000毫秒
方法實際耗時:4000毫秒
結果:真實結果

運行結果2:

任務將耗時: 7000毫秒
方法實際耗時:5037毫秒
結果:超時標誌
任務將耗時: 9000毫秒
方法實際耗時:5001毫秒
結果:超時標誌
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章