并发编程中常用的设计模式有:executor:管理线程池并提交任务,简化线程管理。future:表示异步执行的任务,允许在任务完成前访问结果或取消任务。completablefuture:增强了 future,提供了更复杂的异步流程构建功能。semaphore:限制同时访问特定资源的线程数量,防止资源超载。threadlocal:为每个线程提供私有数据存储,避免线程安全问题。

Java 框架并发编程中的常用设计模式
并发编程在 Java 框架中至关重要,需要有效地协调并行任务。以下是一些最常用的设计模式,可用于简化和有效实现并发代码:
Executor
立即学习“Java免费学习笔记(深入)”;
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> System.out.println("Task completed"));Future
Future<String> future = executor.submit(() -> "Task result"); String result = future.get();
CompletableFuture
CompletableFuture<String> future = new CompletableFuture<>();
executor.submit(() -> {
String result = "Task result";
future.complete(result);
});Semaphore
Semaphore semaphore = new Semaphore(10); // 允许 10 个线程同时访问
semaphore.acquire(); // 获得许可证
try {
// 访问资源
} finally {
semaphore.release(); // 释放许可证
}ThreadLocal
ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("Thread-specific data");
String data = threadLocal.get();实战案例:并发文件读取
以下是一个使用 Executor 和 Future 模式读取文件的并发案例:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.*;
public class FileLinesReader {
private static final int NUM_THREADS = 10;
public static void main(String[] args) throws IOException, InterruptedException {
Path path = Paths.get("input.txt");
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
List<Future<List<String>>> futures = submitFileLinesProcessing(executor, path);
List<String> lines = collectFileLines(futures);
for (String line : lines) {
System.out.println(line);
}
}
private static List<Future<List<String>>> submitFileLinesProcessing(
ExecutorService executor, Path path) throws IOException {
List<Future<List<String>>> futures = new ArrayList<>();
for (int i = 0; i < NUM_THREADS; i++) {
futures.add(executor.submit(() -> Files.readAllLines(path)));
}
return futures;
}
private static List<String> collectFileLines(
List<Future<List<String>>> futures) throws InterruptedException, ExecutionException {
List<String> lines = new ArrayList<>();
for (Future<List<String>> future : futures) {
lines.addAll(future.get());
}
return lines;
}
}以上就是Java框架并发编程中有哪些常用设计模式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号