并发编程是 Java 开发中的核心技能,掌握它能帮助我们构建高性能、高可用的应用程序。本文将深入探讨 Java 并发编程的核心机制。
// 方式1:继承 Thread 类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
// 方式2:实现 Runnable 接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
// 方式3:实现 Callable 接口(带返回值)
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Callable result";
}
}
Java 线程有以下状态:
synchronized 是 Java 最基本的同步机制:
public class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void decrement() {
synchronized (this) {
count--;
}
}
}
ReentrantLock 提供了比 synchronized 更灵活的锁机制:
public class LockDemo {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
public class ProducerConsumer {
private boolean flag = false;
public synchronized void produce() throws InterruptedException {
while (flag) {
wait();
}
flag = true;
notifyAll();
}
}
更推荐使用 BlockingQueue 实现生产者-消费者模式:
BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
queue.put("item");
String item = queue.take();
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> 42);
executor.shutdown();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // 核心线程数
5, // 最大线程数
60L, TimeUnit.SECONDS, // 存活时间
new LinkedBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy()
);
用于等待多个线程完成:
CountDownLatch latch = new CountDownLatch(3);
latch.countDown();
latch.await();
用于线程互相等待:
CyclicBarrier barrier = new CyclicBarrier(3);
barrier.await();
用于控制同时访问的线程数量:
Semaphore semaphore = new Semaphore(2);
semaphore.acquire();
semaphore.release();
保证变量的可见性和有序性:
public class VolatileDemo {
private volatile boolean running = true;
public void stop() {
running = false;
}
}
AtomicInteger、AtomicLong 等提供无锁的原子操作:
AtomicInteger counter = new AtomicInteger(0);
int newValue = counter.incrementAndGet();
线程安全的 HashMap:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.putIfAbsent("key", 0);
map.computeIfPresent("key", (k, v) -> v + 1);
Java 8 引入的异步编程工具:
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> fetchData())
.thenApply(data -> process(data))
.exceptionally(ex -> handleError(ex));
用于分治任务的并行计算:
class SumTask extends RecursiveTask<Long> {
@Override
protected Long compute() {
// 分治计算逻辑
return sum;
}
}
Java 并发编程涉及的知识点非常丰富。掌握这些机制能帮助你编写出高效、可靠的并发程序。建议优先使用 java.util.concurrent 包提供的工具类,它们经过充分优化和测试。