锘??xml version="1.0" encoding="utf-8" standalone="yes"?>蜜臀亚洲AV无码精品国产午夜.,国产亚洲综合成人91精品,一本色道久久88亚洲综合http://m.tkk7.com/paulwong/archive/2020/08/24/435646.htmlpaulwongpaulwongMon, 24 Aug 2020 01:06:00 GMThttp://m.tkk7.com/paulwong/archive/2020/08/24/435646.htmlhttp://m.tkk7.com/paulwong/comments/435646.htmlhttp://m.tkk7.com/paulwong/archive/2020/08/24/435646.html#Feedback0http://m.tkk7.com/paulwong/comments/commentRss/435646.htmlhttp://m.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://m.tkk7.com/paulwong/archive/2020/08/14/435641.htmlpaulwongpaulwongFri, 14 Aug 2020 03:46:00 GMThttp://m.tkk7.com/paulwong/archive/2020/08/14/435641.htmlhttp://m.tkk7.com/paulwong/comments/435641.htmlhttp://m.tkk7.com/paulwong/archive/2020/08/14/435641.html#Feedback0http://m.tkk7.com/paulwong/comments/commentRss/435641.htmlhttp://m.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 鍙戣〃璇勮
]]> 主站蜘蛛池模板: 亚洲伊人久久大香线蕉AV| 亚洲另类古典武侠| 麻豆一区二区三区蜜桃免费| 一本岛高清v不卡免费一三区| 亚洲白色白色在线播放| 国产h肉在线视频免费观看| 亚洲激情视频网站| 91在线视频免费播放| 色偷偷女男人的天堂亚洲网| 毛片免费全部免费观看| 亚洲国产精品ⅴa在线观看| 在线观看视频免费国语| 国产成人精品日本亚洲语音| 免费在线观看中文字幕| 亚洲免费日韩无码系列| 亚洲成AV人片在线观看无码| 99久久国产免费-99久久国产免费| 亚洲精品视频观看| 台湾一级毛片永久免费| 亚洲风情亚Aⅴ在线发布| 亚洲国产成人久久一区久久| 两个人看的www免费视频| 亚洲美女人黄网成人女| 女人与禽交视频免费看 | 亚洲精品亚洲人成在线播放| 成人毛片视频免费网站观看| 另类专区另类专区亚洲| 亚洲成AV人片在线观看ww| 2021免费日韩视频网| 国产AV无码专区亚洲AV麻豆丫| 国产亚洲色婷婷久久99精品91| 久久久久久久99精品免费 | 亚洲AV色香蕉一区二区| 麻豆一区二区免费播放网站| 国产亚洲精品仙踪林在线播放| 水蜜桃亚洲一二三四在线 | 亚洲国产成人爱av在线播放 | 午夜毛片不卡高清免费| 一区二区三区在线免费观看视频| 中文字幕亚洲精品资源网| 免费A级毛片无码A|