Java 并发编程核心机制详解

并发编程是 Java 开发中的核心技能,掌握它能帮助我们构建高性能、高可用的应用程序。本文将深入探讨 Java 并发编程的核心机制。

一、线程基础

1.1 创建线程的三种方式

// 方式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";
    }
}

1.2 线程状态转换

Java 线程有以下状态:

  • NEW: 新建状态
  • RUNNABLE: 可运行状态
  • BLOCKED: 阻塞状态
  • WAITING: 等待状态
  • TIMED_WAITING: 限时等待
  • TERMINATED: 终止状态

二、线程同步机制

2.1 synchronized 关键字

synchronized 是 Java 最基本的同步机制:

public class Counter {
    private int count = 0;
    
    // 同步方法
    public synchronized void increment() {
        count++;
    }
    
    // 同步代码块
    public void decrement() {
        synchronized (this) {
            count--;
        }
    }
}

2.2 ReentrantLock

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();
        }
    }
}

三、线程间通信

3.1 wait/notify 机制

public class ProducerConsumer {
    private boolean flag = false;
    
    public synchronized void produce() throws InterruptedException {
        while (flag) {
            wait();
        }
        flag = true;
        notifyAll();
    }
}

3.2 BlockingQueue

更推荐使用 BlockingQueue 实现生产者-消费者模式:

BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
queue.put("item");
String item = queue.take();

四、线程池

4.1 Executor 框架

ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> 42);
executor.shutdown();

4.2 自定义线程池参数

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    2,                      // 核心线程数
    5,                      // 最大线程数
    60L, TimeUnit.SECONDS,  // 存活时间
    new LinkedBlockingQueue<>(100),
    new ThreadPoolExecutor.CallerRunsPolicy()
);

五、并发工具类

5.1 CountDownLatch

用于等待多个线程完成:

CountDownLatch latch = new CountDownLatch(3);
latch.countDown();
latch.await();

5.2 CyclicBarrier

用于线程互相等待:

CyclicBarrier barrier = new CyclicBarrier(3);
barrier.await();

5.3 Semaphore

用于控制同时访问的线程数量:

Semaphore semaphore = new Semaphore(2);
semaphore.acquire();
semaphore.release();

六、volatile 关键字

保证变量的可见性和有序性:

public class VolatileDemo {
    private volatile boolean running = true;
    
    public void stop() {
        running = false;
    }
}

七、原子类

AtomicInteger、AtomicLong 等提供无锁的原子操作:

AtomicInteger counter = new AtomicInteger(0);
int newValue = counter.incrementAndGet();

八、ConcurrentHashMap

线程安全的 HashMap:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.putIfAbsent("key", 0);
map.computeIfPresent("key", (k, v) -> v + 1);

九、CompletableFuture

Java 8 引入的异步编程工具:

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> fetchData())
    .thenApply(data -> process(data))
    .exceptionally(ex -> handleError(ex));

十、Fork/Join 框架

用于分治任务的并行计算:

class SumTask extends RecursiveTask<Long> {
    @Override
    protected Long compute() {
        // 分治计算逻辑
        return sum;
    }
}

总结

Java 并发编程涉及的知识点非常丰富。掌握这些机制能帮助你编写出高效、可靠的并发程序。建议优先使用 java.util.concurrent 包提供的工具类,它们经过充分优化和测试。