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

Java 框架并发编程中的常用设计模式
并发编程在 Java 框架中至关重要,需要有效地协调并行任务。以下是一些最常用的设计模式,可用于简化和有效实现并发代码:
Executor
立即学习“Java免费学习笔记(深入)”;
- 用途:管理线程池并提交任务。
- 好处:抽象了线程管理,提供了动态扩展和优化性能的方法。
- 示例:
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> System.out.println("Task completed"));Future
UQCMS云商是一款B2B2C电子商务软件 ,非常适合初创的创业者,个人及中小型企业。程序采用PHP+MYSQL,模板采用smarty模板,二次开发,简单方便,无需学习其他框架就可以自行模板设计。永久免费使用,操作简单,安全稳定。支持PC+WAP+微信三种浏览方式,支持微信公众号。
- 用途:表示异步执行的任务。
- 好处:允许在任务完成之前访问结果或取消任务。
- 示例:
Futurefuture = executor.submit(() -> "Task result"); String result = future.get();
CompletableFuture
- 用途:增强了 Future,提供了更多的并发功能,例如组合和转换任务。
- 好处:允许轻松构建复杂的异步流程。
- 示例:
CompletableFuturefuture = 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
- 用途:为每个线程提供其自己的私有数据存储。
- 好处:避免线程安全问题,轻松访问线程特定数据。
- 示例:
ThreadLocalthreadLocal = 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>> futures = submitFileLinesProcessing(executor, path);
List lines = collectFileLines(futures);
for (String line : lines) {
System.out.println(line);
}
}
private static List>> submitFileLinesProcessing(
ExecutorService executor, Path path) throws IOException {
List>> futures = new ArrayList<>();
for (int i = 0; i < NUM_THREADS; i++) {
futures.add(executor.submit(() -> Files.readAllLines(path)));
}
return futures;
}
private static List collectFileLines(
List>> futures) throws InterruptedException, ExecutionException {
List lines = new ArrayList<>();
for (Future> future : futures) {
lines.addAll(future.get());
}
return lines;
}
}









