多线程编程是 Java 开发中的核心技能之一,掌握常见设计模式能显著提升并发处理能力。以下是 5 个高频使用的模式及实战要点:
🧠 1. 生产者-消费者模式
// 使用 BlockingQueue 实现
BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
new Thread(() -> {
for (int i = 0; i < 20; i++) {
queue.put("Item_" + i);
System.out.println("Produced: " + i);
}
}).start();
new Thread(() -> {
for (int i = 0; i < 20; i++) {
String item = queue.take();
System.out.println("Consumed: " + item);
}
}).start();
🧩 2. 线程池模式
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
pool.submit(() -> System.out.println("Task executed by " + Thread.currentThread().getName()));
}
pool.shutdown();
关键点:通过 ThreadPoolExecutor
自定义核心参数,合理控制资源利用率。
🔒 3. 读写锁模式
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock();
try {
// 读操作
} finally {
lock.readLock().unlock();
}
适用场景:适用于读多写少的场景,如缓存数据访问。
🧹 4. 守护线程模式
new Thread(() -> {
while (true) {
// 清理任务
try { Thread.sleep(1000); } catch (Exception e) {}
}
}, "Cleanup-Thread").setDaemon(true).start();
注意:守护线程随主线程退出自动终止,常用于后台服务。
⚙️ 5. 同步器模式(如 Semaphore)
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println("Thread " + Thread.currentThread().getName() + " is running");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, "Worker-" + i).start();
}
扩展学习:
想深入理解线程安全与并发工具?点击 Java 并发工具类详解 获取更多实战技巧 ✅