锘??xml version="1.0" encoding="utf-8" standalone="yes"?>国产精品美女一区二区三区,中文国产一区,国产精品美女wwwhttp://www.aygfsteel.com/paulwong/archive/2020/08/24/435646.htmlpaulwongpaulwongMon, 24 Aug 2020 01:06:00 GMThttp://www.aygfsteel.com/paulwong/archive/2020/08/24/435646.htmlhttp://www.aygfsteel.com/paulwong/comments/435646.htmlhttp://www.aygfsteel.com/paulwong/archive/2020/08/24/435646.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/435646.htmlhttp://www.aygfsteel.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.aygfsteel.com/paulwong/archive/2020/08/14/435641.htmlpaulwongpaulwongFri, 14 Aug 2020 03:46:00 GMThttp://www.aygfsteel.com/paulwong/archive/2020/08/14/435641.htmlhttp://www.aygfsteel.com/paulwong/comments/435641.htmlhttp://www.aygfsteel.com/paulwong/archive/2020/08/14/435641.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/435641.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/435641.html
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start(); // 鍚姩鏂扮嚎紼?/span>
t2.start(); // 鍚姩鏂扮嚎紼?/span>

鐢變簬鍒涘緩鍜岄攢姣佺嚎紼嬫槸闈炲父鑰楄祫婧愶紝鍥犳鏀規垚綰跨▼寤哄ソ鍚庝笉閿姣侊紝鍙互閲嶇敤錛岀敤鎴峰彧闇鎻愪緵run鏂規硶鐨勫叿浣撳疄鐜幫細
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 鍙戣〃璇勮
]]> 主站蜘蛛池模板: 鹿邑县| 孝感市| 铜陵市| 九江县| 基隆市| 通辽市| 项城市| 栾川县| 正蓝旗| 榆中县| 毕节市| 大余县| 娱乐| 增城市| 晋江市| 太原市| 恩平市| 和顺县| 陆丰市| 齐齐哈尔市| 方正县| 南昌市| 南部县| 常熟市| 安溪县| 新泰市| 罗江县| 屯门区| 深州市| 白沙| 邯郸市| 金昌市| 昂仁县| 富源县| 五指山市| 甘孜县| 调兵山市| 二连浩特市| 铜川市| 岳阳市| 鄂尔多斯市|