Java 并发编程是提升程序性能和响应能力的重要技术。本文系统介绍 Java 并发的基础知识、常用工具与实战技巧,帮助你从容应对多线程开发挑战。


一、Java 并发基础

Java 中创建线程主要有两种方式:

1. 继承 Thread 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}

new MyThread().start();
````

### 2. 实现 Runnable 接口

```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}

new Thread(new MyRunnable()).start();

推荐使用 Runnable,因为它避免了单继承限制。


二、线程安全与同步

多线程共享资源时,必须保证线程安全。常见方法:

1. synchronized 关键字

1
2
3
public synchronized void increment() {
count++;
}

2. Lock 接口(ReentrantLock)

1
2
3
4
5
6
7
Lock lock = new ReentrantLock();
lock.lock();
try {
count++;
} finally {
lock.unlock();
}

3. 原子变量(AtomicInteger)

1
2
AtomicInteger atomicCount = new AtomicInteger(0);
atomicCount.incrementAndGet();

三、线程池(Executor 框架)

线程池复用线程资源,避免频繁创建销毁带来的性能开销。

1
2
3
4
5
6
7
ExecutorService executor = Executors.newFixedThreadPool(5);

executor.submit(() -> {
System.out.println("Thread pool task running");
});

executor.shutdown();

常用线程池类型:

  • FixedThreadPool:固定线程数
  • CachedThreadPool:可缓存线程池,自动回收空闲线程
  • ScheduledThreadPool:支持定时及周期任务

四、并发工具类

Java 提供丰富的并发辅助类:

  • CountDownLatch:用于等待其他线程完成
  • CyclicBarrier:多线程互相等待,达到同步点再继续
  • Semaphore:控制访问资源的线程数量
  • BlockingQueue:线程安全的队列,常用于生产者消费者模式

五、实战场景示例

1. 生产者消费者模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

Runnable producer = () -> {
try {
queue.put("item");
} catch (InterruptedException e) { }
};

Runnable consumer = () -> {
try {
String item = queue.take();
System.out.println("Consumed: " + item);
} catch (InterruptedException e) { }
};

new Thread(producer).start();
new Thread(consumer).start();

2. 使用线程池执行大量任务

1
2
3
4
5
6
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
int taskId = i;
pool.submit(() -> System.out.println("Task " + taskId + " executed"));
}
pool.shutdown();

六、并发编程注意事项

  • 避免死锁:谨慎设计锁的获取顺序
  • 合理选择同步粒度,避免性能瓶颈
  • 谨慎使用共享变量,优先考虑无状态设计
  • 使用并发容器替代非线程安全集合(如 ConcurrentHashMap