在调用三方API时,对某些特殊的接口要求响应时间比较高,如果响应超时后可继续执行其它逻辑的处理方法。

public class LimitedTimeExecutor {

    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(1);

    class Task implements Callable<String>{

        @Override
        public String call() throws Exception {
            //调用外部接口或处理耗时的操作
            TimeUnit.SECONDS.sleep(4);
            return "Hello World";
        }
    }

    public void exec(){
        FutureTask<String> futureTask = new FutureTask<>(new Task());
        THREAD_POOL.execute(futureTask);
        try {
            String result = futureTask.get(3, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("Invoke timeout");
        }
        //继续处理其它逻辑
        System.out.println("Go on");
    }

    public static void main(String[] args) {
        LimitedTimeExecutor demo = new LimitedTimeExecutor();
        demo.exec();
        THREAD_POOL.shutdown();
    }
}

发表评论