一、生产者-消费者模式 1.1 核心思想 生产者线程 → [队列] → 消费者线程 - 生产者:生产数据,放入队列 - 消费者:从队列取出数据,处理 - 队列:解耦生产者和消费者 优势:
✅ 解耦:生产者和消费者独立 ✅ 削峰填谷:队列缓冲,应对突发流量 ✅ 异步处理:提高响应速度 1.2 BlockingQueue实现 public class ProducerConsumerDemo { private BlockingQueue<Task> queue = new LinkedBlockingQueue<>(100); // 生产者 class Producer implements Runnable { @Override public void run() { while (true) { try { Task task = produceTask(); queue.put(task); // 队列满时阻塞 System.out.println("生产:" + task); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } private Task produceTask() { // 生产任务 return new Task(); } } // 消费者 class Consumer implements Runnable { @Override public void run() { while (true) { try { Task task = queue.take(); // 队列空时阻塞 processTask(task); System.out.println("消费:" + task); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } private void processTask(Task task) { // 处理任务 } } public static void main(String[] args) { ProducerConsumerDemo demo = new ProducerConsumerDemo(); // 启动3个生产者 for (int i = 0; i < 3; i++) { new Thread(demo.new Producer()).start(); } // 启动5个消费者 for (int i = 0; i < 5; i++) { new Thread(demo.new Consumer()).start(); } } } 二、线程池模式 2.1 核心思想 任务提交 → [线程池] → 线程执行 - 预创建线程,复用线程资源 - 避免频繁创建/销毁线程的开销 - 控制并发数量,避免资源耗尽 2.2 自定义线程池 public class CustomThreadPool { private final BlockingQueue<Runnable> taskQueue; private final List<WorkerThread> workers; private volatile boolean isShutdown = false; public CustomThreadPool(int poolSize, int queueSize) { taskQueue = new LinkedBlockingQueue<>(queueSize); workers = new ArrayList<>(poolSize); // 创建工作线程 for (int i = 0; i < poolSize; i++) { WorkerThread worker = new WorkerThread(); workers.add(worker); worker.start(); } } // 提交任务 public void submit(Runnable task) { if (isShutdown) { throw new IllegalStateException("线程池已关闭"); } try { taskQueue.put(task); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } // 关闭线程池 public void shutdown() { isShutdown = true; for (WorkerThread worker : workers) { worker.interrupt(); } } // 工作线程 private class WorkerThread extends Thread { @Override public void run() { while (!isShutdown) { try { Runnable task = taskQueue.take(); task.run(); } catch (InterruptedException e) { break; } } } } } 三、Future模式 3.1 核心思想 主线程提交任务 → 异步执行 → 主线程继续工作 → 需要时获取结果 - 异步获取结果 - 主线程不阻塞 - 提高并发性能 3.2 简化实现 public class FutureDemo { // 自定义Future class FutureResult<T> { private volatile T result; private volatile boolean isDone = false; public void set(T result) { this.result = result; this.isDone = true; synchronized (this) { notifyAll(); // 唤醒等待线程 } } public T get() throws InterruptedException { if (!isDone) { synchronized (this) { while (!isDone) { wait(); // 等待结果 } } } return result; } } // 异步任务 public FutureResult<String> asyncTask() { FutureResult<String> future = new FutureResult<>(); new Thread(() -> { // 模拟耗时操作 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // 设置结果 future.set("异步任务完成"); }).start(); return future; // 立即返回Future } public static void main(String[] args) throws InterruptedException { FutureDemo demo = new FutureDemo(); // 提交异步任务 FutureResult<String> future = demo.asyncTask(); // 主线程继续工作 System.out.println("主线程继续工作..."); // 需要时获取结果 String result = future.get(); System.out.println("结果:" + result); } } 四、不变模式(Immutable Pattern) 4.1 核心思想 对象创建后,状态不可改变 - 无需同步:线程安全 - 简化并发:无竞态条件 - 高性能:无锁开销 4.2 实现方式 // 不变对象 public final class ImmutablePoint { private final int x; private final int y; public ImmutablePoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } // 修改操作返回新对象 public ImmutablePoint move(int deltaX, int deltaY) { return new ImmutablePoint(x + deltaX, y + deltaY); } } // 使用 ImmutablePoint p1 = new ImmutablePoint(0, 0); ImmutablePoint p2 = p1.move(10, 10); // 新对象 // 多线程安全:p1和p2都不会被修改 关键要素:
...