Asynchrone Programmierung mit Java, runAsync und supplyAsync

avatar

Beispiele wie die asynchrone Programmierung in Java funktioniert.
Die keywords async und await gibt es nicht in Java. Stattdessen wird dieses Konzept mit den CompletableFuture realisiert.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class Asynchron {

    /** dummy function for delay */
    private int delay(int seconds){
        try {
            TimeUnit.SECONDS.sleep(seconds);
            return 15;
        } catch ( InterruptedException e){
            e.printStackTrace();
            return -1;
        }
    }

    /** runAsync, if there is no need to return something */
    public void runAsyncTest(){
        ExecutorService worker = Executors.newFixedThreadPool(4); 

        /* create a runnable object */
        Runnable run = () -> {
            delay(4);
            System.out.println("Inside Runnable: "+Thread.currentThread().getName());
        };

        /* CompletableFuture does the async part */
        CompletableFuture<Void> future = CompletableFuture.runAsync(run, worker);
        System.out.println("Inside Main: "+Thread.currentThread().getName());
        future.join();
    }

    /** supplyAsync, if a return type is needed */
    public void supplyAsyncTest(){
        ExecutorService worker = Executors.newFixedThreadPool(4); 
    
        /* create a supplier object */
        Supplier<Integer> result = () -> {
            int value = delay(3);
            System.out.println("Inside Runnable: "+Thread.currentThread().getName());
            return value;
        };
    
        /* CompletableFuture does the async part */
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(result, worker);
        System.out.println("Inside Main: "+Thread.currentThread().getName());
        int fromFuture = future.join();
        System.out.println(fromFuture);
    }

    public static void main(String[] args){
        Asynchron async = new Asynchron();
        async.runAsyncTest();
        async.supplyAsyncTest();
    }
}



0
0
0.000
0 comments