-
线程的实现方式
-
java 多线程之 extends Thread
-
java 多线程之 implements Runnable
-
java 多线程之 implements Callable
-
-
线程池的使用
-
线程池简介
-
ThreadPoolExecutor
-
java 线程池之 newScheduledThreadPool
-
java 线程池之 newCachedThreadPool
-
java 线程池之 newFixedThreadPool
-
java 线程池之 newSingleThreadExecutor
-
-
ForkJoinPool
-
java 线程池之 newWorkStealingPool
-
-
CompletableFuture
-
CompletableFuture 的使用示例
-
-
import lombok.SneakyThrows;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CompletableRunnable {
public void runAsync() {
// 默认 线程池
CompletableFuture.runAsync(() -> {
System.out.println("runAsync 使用示例");
});
// 自定义 线程池
CompletableFuture.runAsync(() -> {
System.out.println("runAsync 使用示例");
}, this.getPoolExecutor());
}
@SneakyThrows
public void supplyAsync() {
// 默认 线程池
String supplyAsync1 = CompletableFuture.supplyAsync(() -> "runAsync 使用示例")
.get();
System.out.println(supplyAsync1);
// 自定义 线程池
String supplyAsync2 = CompletableFuture.supplyAsync(() -> "runAsync 使用示例")
.get();
System.out.println(supplyAsync2);
}
@SneakyThrows
public void anyOf() {
// 运行 runAsync1
CompletableFuture runAsync1 = CompletableFuture.runAsync(() -> {
System.out.println("runAsync1 运行");
});
// 运行 runAsync2
CompletableFuture runAsync2 = CompletableFuture.runAsync(() -> {
System.out.println("runAsync2 运行");
}, this.getPoolExecutor());
// 等待任意线程执行完成继续
Object join = CompletableFuture.anyOf(runAsync1, runAsync2)
.join();
System.out.println(join);
}
@SneakyThrows
public void allOf() {
// 运行 runAsync1
CompletableFuture runAsync1 = CompletableFuture.runAsync(() -> {
System.out.println("runAsync1 运行");
});
// 运行 runAsync2
CompletableFuture runAsync2 = CompletableFuture.runAsync(() -> {
System.out.println("runAsync2 运行");
}, this.getPoolExecutor());
// 等待全部线程执行完成再继续
Object join = CompletableFuture.allOf(runAsync1, runAsync2)
.join();
System.out.println(join);
}
private ThreadPoolExecutor getPoolExecutor() {
return new ThreadPoolExecutor(1, 1, 0
, TimeUnit.SECONDS, new LinkedBlockingDeque<>(10));
}
} 


