Published: 07 Mar 2023 › Updated: 07 Mar 2023
Asynchrone Programmierung mit Java, runAsync und supplyAsync
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();
}
}
Leave Asynchrone Programmierung mit Java, runAsync und supplyAsync to:
Read more #stemgeeks posts
Best Posts From ozelot47
We have not curated any of ozelot47's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From ozelot47
- Ion Fury, Level 8: Defense Farce
- Funktionalgleichung mit Parameter
- Ion Fury, Level 7: Alphabet Soup
- Funktionalgleichung mit Brüchen
- Eine Funktionalgleichung lösen
- Integral in Kombination mit der Substitution und Produktintegration lösen
- Ion Fury, Level 6: Abandonment Issues
- Beispiel einer Exponentialgleichung mithilfe der Substitution lösen
- Ein schöner Sonntagsspaziergang
- Ion Fury, Level 5: Reformation Plaza