首页  编辑  

Java异步单独执行

Tags: /Java/   Date Created:

 private static void singleWait() {
        CompletableFuture<String> timeoutFuture = CompletableFuture
                .supplyAsync(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    return "single done";
                })
                .completeOnTimeout("timeout"2, TimeUnit.SECONDS);
        log.info(String.valueOf(LocalDateTime.now()));

        try {
            String result = timeoutFuture.get();
            // 阻塞
            log.info(String.valueOf(LocalDateTime.now()));
            log.info(result);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }