帮我用java写一个通过CompletableFuture实现任务调度的demo
时间: 2024-02-11 19:05:58 浏览: 99
好的,这里是一个通过CompletableFuture实现任务调度的Java demo,代码如下:
```java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
System.out.println("Task 1 started...");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 1 completed!");
});
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
System.out.println("Task 2 started...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 2 completed!");
});
CompletableFuture<Void> future3 = CompletableFuture.runAsync(() -> {
System.out.println("Task 3 started...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 3 completed!");
});
CompletableFuture<Void> future4 = CompletableFuture.runAsync(() -> {
System.out.println("Task 4 started...");
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 4 completed!");
});
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3, future4);
allFutures.get();
}
}
```
这个demo中,我们使用了四个CompletableFuture对象来模拟四个任务,并通过CompletableFuture.allOf()方法来等待所有任务完成。其中,每个任务都是通过runAsync()方法提交到默认的ForkJoinPool中执行的,这里我们使用了TimeUnit来模拟每个任务的执行时间。
阅读全文