锘??xml version="1.0" encoding="utf-8" standalone="yes"?>蜜臀亚洲AV无码精品国产午夜.,国产亚洲综合成人91精品,一本色道久久88亚洲综合http://www.tkk7.com/paulwong/archive/2020/08/24/435646.htmlpaulwongpaulwongMon, 24 Aug 2020 01:06:00 GMThttp://www.tkk7.com/paulwong/archive/2020/08/24/435646.htmlhttp://www.tkk7.com/paulwong/comments/435646.htmlhttp://www.tkk7.com/paulwong/archive/2020/08/24/435646.html#Feedback0http://www.tkk7.com/paulwong/comments/commentRss/435646.htmlhttp://www.tkk7.com/paulwong/services/trackbacks/435646.htmlWhen we want to do something later in our Java code, we often turn to the ScheduledExecutorService. This class has a method called schedule(), and we can pass it some code to be run later like this:

ScheduledExecutorService executor =
    Executors.newScheduledThreadPool(4);
executor.schedule(
    () -> {System.out.println("..later");},
    1,
    TimeUnit.SECONDS
);
System.out.println("do");
// (Don't forget to shut down the executor later)

The above code prints “do…” and then one second later it prints “…later”.

We can even write code that does some work and returns a result in a similar way:

// (Make the executor as above.)
ScheduledFuture future = executor.schedule(
    () -> 10 + 25, 1, TimeUnit.SECONDS);
System.out.println("answer=" + future.get())


The above code prints “answer=35”. When we call get() it blocks waiting for the scheduler to run the task and mark the ScheduledFuture as complete, and then returns the answer to the sum (10 + 25) when it is ready.

This is all very well, but you may note that the Future returned from schedule() is a ScheduledFuture, and a ScheduledFuture is not a CompletableFuture.

Why do you care? Well, you might care if you want to do something after the scheduled task is completed. Of course, you can call get(), and block, and then do something, but if you want to react asynchronously without blocking, this won’t work.

The normal way to run some code after a Future has completed is to call one of the “then*” or “when*” methods on the Future, but these methods are only available on CompletableFuture, not ScheduledFuture.

Never fear, we have figured this out for you. We present a small wrapper for schedule that transforms your ScheduledFuture into a CompletableFuture. Here’s how to use it:

CompletableFuture<Integer> future =
    ScheduledCompletable.schedule(
        executor,
        () -> 10 + 25,
        1,
        TimeUnit.SECONDS
     );
future.thenAccept(
    answer -> {System.out.println(answer);}
);
System.out.println("Answer coming")


The above code prints “Answer coming…” and then “35”, so we can see that we don’t block the main thread waiting for the answer to come back.

So far, we have scheduled a synchronous task to run in the background after a delay, and wrapped its result in a CompletableFuture to allow us to chain more tasks after it.

In fact, what we often want to do is schedule a delayed task that is itself asynchronous, and already returns a CompletableFuture. In this case it feels particularly natural to get the result back as a CompletableFuture, but with the current ScheduledExecutorService interface we can’t easily do it.

It’s OK, we’ve figured that out too:

Supplier<CompletableFuture<Integer>> asyncTask = () ->
    CompletableFuture.completedFuture(10 + 25);
CompletableFuture<Integer> future =
    ScheduledCompletable.scheduleAsync(
        executor, asyncTask, 1, TimeUnit.SECONDS);
future.thenAccept(
    answer -> {System.out.println(answer);}
);
System.out.println("Answer coming")


The above code prints “Answer coming…” and then “35”, so we can see that our existing asynchronous task was scheduled in the background, and we didn’t have to block the main thread waiting for it. Also, under the hood, we are not blocking the ScheduledExecutorService‘s thread (from its pool) while the async task is running – that task just runs in whatever thread it was assigned when it was created. (Note: in our example we don’t really run an async task at all, but just immediately return a completed Future, but this does work for real async tasks.)

I know you’re wondering how we achieved all this. First, here’s how we run a simple blocking task in the background and wrap it in a CompletableFuture:

public static <T> CompletableFuture<T> schedule(
    ScheduledExecutorService executor,
    Supplier<T> command,
    long delay,
    TimeUnit unit
) {
    CompletableFuture<T> completableFuture = new CompletableFuture<>();
    executor.schedule(
        (() -> {
            try {
                return completableFuture.complete(command.get());
            } catch (Throwable t) {
                return completableFuture.completeExceptionally(t);
            }
        }),
        delay,
        unit
    );
    return completableFuture;
}


And here’s how we delay execution of an async task but still return its result in a CompletableFuture:

public static <T> CompletableFuture<T> scheduleAsync(
    ScheduledExecutorService executor,
    Supplier<CompletableFuture<T>> command,
    long delay,
    TimeUnit unit
) {
    CompletableFuture<T> completableFuture = new CompletableFuture<>();
    executor.schedule(
        (() -> {
            command.get().thenAccept(
                t -> {completableFuture.complete(t);}
            )
            .exceptionally(
                t -> {completableFuture.completeExceptionally(t);return null;}
            );
        }),
        delay,
        unit
    );
    return completableFuture;
}


Note that this should all work to run methods like exceptionally()thenAccept()whenComplete() etc.

Feedback and improvements welcome!


https://www.artificialworlds.net/blog/2019/04/05/scheduling-a-task-in-java-within-a-completablefuture/

paulwong 2020-08-24 09:06 鍙戣〃璇勮
]]>
CompletableFuturehttp://www.tkk7.com/paulwong/archive/2020/08/14/435641.htmlpaulwongpaulwongFri, 14 Aug 2020 03:46:00 GMThttp://www.tkk7.com/paulwong/archive/2020/08/14/435641.htmlhttp://www.tkk7.com/paulwong/comments/435641.htmlhttp://www.tkk7.com/paulwong/archive/2020/08/14/435641.html#Feedback0http://www.tkk7.com/paulwong/comments/commentRss/435641.htmlhttp://www.tkk7.com/paulwong/services/trackbacks/435641.html
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start(); // 鍚姩鏂扮嚎紼?/span>
t2.start(); // 鍚姩鏂扮嚎紼?/span>

鐢變簬鍒涘緩鍜岄攢姣佺嚎紼嬫槸闈炲父鑰楄祫婧愶紝鍥犳鏀規(guī)垚綰跨▼寤哄ソ鍚庝笉閿姣侊紝鍙互閲嶇敤錛岀敤鎴峰彧闇鎻愪緵run鏂規(guī)硶鐨勫叿浣撳疄鐜幫細(xì)
public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> stringFuture = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "async thread";
            }
        });
        Thread.sleep(1000);
        System.out.println("main thread");
        System.out.println(stringFuture.get());

    }

浣嗗鏋滃緢澶氱嚎紼嬭鍒涘緩錛屽茍涓旂嚎紼嬮棿鏈変緷璧栵紝鍗蟲寜嫻佺▼鍜屾潯浠舵墽琛岀嚎紼嬶紝瀹炵幇璧鋒潵灝辨湁鐐瑰鏉傦紝浜庢槸CompletableFuture妯┖鍑轟笘銆備竴鍏辨湁50鍚勬柟娉曞彲渚涗嬌鐢ㄣ?br />
CompletableFuture.supplyAsync()錛岀浉褰撲簬鍒涘緩浜咵xecutorService錛屽悓鏃朵篃鍒涘緩浜咰allable錛岀劧鍚庢彁浜ゅ埌綰跨▼姹犱腑鎵ц銆?/div>
CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "浠誨姟A");
CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> "浠誨姟B");
CompletableFuture<String> futureC = futureB.thenApply(b -> {
      System.out.println("鎵ц浠誨姟C.");
      System.out.println("鍙傛暟:" + b);//鍙傛暟:浠誨姟B
      return "a";
});


!!How to use CompletableFuture and Callable in Java
https://ducmanhphan.github.io/2020-02-10-How-to-use-CompletableFuture-Callable-in-Java/

浣跨敤CompletableFuture浼樺寲浣犵殑浠g爜鎵ц鏁堢巼
https://www.cnblogs.com/fingerboy/p/9948736.html

CompletableFuture 浣跨敤璇﹁В
https://www.jianshu.com/p/6bac52527ca4

浣跨敤CompletableFuture
https://www.liaoxuefeng.com/wiki/1252599548343744/1306581182447650


https://github.com/eugenp/tutorials/blob/master/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java

paulwong 2020-08-14 11:46 鍙戣〃璇勮
]]> 主站蜘蛛池模板: 97国产免费全部免费观看| 久久国产精品免费看| 毛片在线免费视频| 亚洲男人的天堂久久精品| 成人免费视频69| 亚洲18在线天美| 全免费a级毛片免费看无码| 亚洲精华国产精华精华液网站| 操美女视频免费网站| 亚洲美国产亚洲AV| 日本成人免费在线| 青青草97国产精品免费观看| ZZIJZZIJ亚洲日本少妇JIZJIZ | 亚洲性无码一区二区三区| 猫咪社区免费资源在线观看| 亚洲色无码专区一区| 免费永久看黄在线观看app| 人妻巨大乳hd免费看| 久久久久亚洲AV无码专区首| 最近2019中文字幕免费直播| 久久亚洲最大成人网4438| 狠狠久久永久免费观看| 视频免费1区二区三区| 亚洲av无码潮喷在线观看| 麻豆视频免费播放| 国产成人综合亚洲一区| 国产亚洲美女精品久久久2020| 日韩av无码久久精品免费| 亚洲香蕉久久一区二区三区四区| 国产中文字幕免费| 成人黄网站片免费视频| 亚洲乱码一区av春药高潮| 免费在线观看你懂的| 三年片在线观看免费观看大全一 | 99久久免费国产精品特黄| 亚洲AV成人一区二区三区观看 | 亚洲视频在线观看免费| 亚洲狠狠婷婷综合久久| 亚洲精品乱码久久久久久蜜桃不卡| 0588影视手机免费看片| 免费又黄又爽又猛大片午夜|