目录
前言:
异步编程相关实现方式:
Java8 Stream简单实现:
并行操作:
详细代码:
输出结果:
异步操作:
详细代码:
结果输出:
Java CompletableFuture异步操作的示例:
CompletableFuture 和 CompletableFuture.delayedExecutor 方法
输出结果:
主要是记录个笔记,对你有帮助的话,那就更好啦
回调函数(Callback):通过在方法调用中传递回调函数,可以在异步操作完成后执行回调方法。
Future和CompletableFuture:Future用于异步操作的结果获取,CompletableFuture则提供了更多的方法,例如thenApply、thenCombine等,可以方便地进行异步操作的组合和串联。
RxJava:提供了丰富的异步编程方法,例如Observable、Subject、Scheduler等,支持异步操作的组合和流式处理。
Java 8 Stream API:提供了类似于函数式编程的操作方式,可以方便地进行并行处理和异步操作的组合。
Java 9 Flow API:提供了Reactive Streams的实现,支持异步消息传递和背压控制。
CompletableFuture和Stream API的结合:Java 9引入的新特性,可以将Stream API和CompletableFuture结合起来使用,实现更加方便的异步编程。
List list = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig");
// 串行处理
list.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
// 并行处理
list.parallelStream()
.map(String::toUpperCase)
.forEach(System.out::println);
import java.util.Arrays;
public class StreamParallelDemo {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 串行流
Arrays.stream(nums)
.map(StreamParallelDemo::process)
.forEach(System.out::println);
// 并行流
Arrays.stream(nums)
.parallel()
.map(StreamParallelDemo::process)
.forEach(System.out::println);
}
public static int process(int num) {
System.out.println("Processing " + num + " in thread " + Thread.currentThread().getName());
return num * 2;
}
}
Processing 1 in thread main
2
Processing 2 in thread main
4
Processing 3 in thread main
6
Processing 4 in thread main
8
Processing 5 in thread main
10
Processing 6 in thread main
12
Processing 7 in thread main
14
Processing 8 in thread main
16
Processing 9 in thread main
18
Processing 10 in thread main
20
Processing 1 in thread ForkJoinPool.commonPool-worker-1
Processing 2 in thread ForkJoinPool.commonPool-worker-2
Processing 3 in thread ForkJoinPool.commonPool-worker-3
Processing 4 in thread ForkJoinPool.commonPool-worker-4
Processing 5 in thread ForkJoinPool.commonPool-worker-5
Processing 6 in thread ForkJoinPool.commonPool-worker-6
Processing 7 in thread ForkJoinPool.commonPool-worker-7
Processing 8 in thread ForkJoinPool.commonPool-worker-8
Processing 9 in thread ForkJoinPool.commonPool-worker-1
Processing 10 in thread ForkJoinPool.commonPool-worker-2
2
4
6
8
10
12
14
16
18
20
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
// 异步操作,返回一个结果
return 42;
});
// 处理异步操作的结果
future.thenAccept(System.out::println);
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class StreamAsyncDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
CompletableFuture[] futures = Arrays.stream(nums)
.mapToObj(StreamAsyncDemo::processAsync)
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
for (CompletableFuture future : futures) {
System.out.println(future.get());
}
}
public static CompletableFuture processAsync(int num) {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Processing " + num + " in thread " + Thread.currentThread().getName());
return num * 2;
});
}
}
Processing 1 in thread ForkJoinPool.commonPool-worker-1
Processing 2 in thread ForkJoinPool.commonPool-worker-2
Processing 3 in thread ForkJoinPool.commonPool-worker-3
Processing 4 in thread ForkJoinPool.commonPool-worker-4
Processing 5 in thread ForkJoinPool.commonPool-worker-5
Processing 6 in thread ForkJoinPool.commonPool-worker-6
Processing 7 in thread ForkJoinPool.commonPool-worker-7
Processing 8 in thread ForkJoinPool.commonPool-worker-8
Processing 9 in thread ForkJoinPool.commonPool-worker-1
Processing 10 in thread ForkJoinPool.commonPool-worker-2
2
4
6
8
10
12
14
16
18
20
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个CompletableFuture对象
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
try {
// 模拟耗时操作
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, CompletableFuture!";
});
// 注册回调函数,当异步操作完成时执行
future.thenAccept(result -> System.out.println(result));
// 阻塞当前线程,等待异步操作完成
String result = future.get();
System.out.println(result);
}
}
supplyAsync
方法执行一个耗时操作。然后我们注册了一个回调函数,在异步操作完成时执行,输出异步操作的结果。最后使用get
方法阻塞当前线程,等待异步操作完成,并输出异步操作的结果。Thread.sleep
等阻塞方法,否则会影响其他线程的执行。应当使用CompletableFuture.delayedExecutor
等方法实现延迟执行。import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture future = CompletableFuture.runAsync(() -> {
// 执行异步任务
System.out.println("异步任务开始执行...");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步任务执行完成!");
}, CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS)); // 延迟 5 秒执行
System.out.println("主线程继续执行...");
future.join(); // 等待异步任务执行完成
}
}
主线程继续执行...
异步任务开始执行...
异步任务执行完成!