### Java多线程编程:从基础概念到高级实践

#### 一、多线程基础概念

1. 进程与线程

- 进程是操作系统资源分配的基本单位,拥有独立的内存空间

- 线程是CPU调度的基本单位,共享进程资源

- Java线程通过java.lang.Thread类实现

2. 线程生命周期

- NEW:新建状态

- RUNNABLE:可运行状态

- BLOCKED:阻塞状态

- WAITING:等待状态

- TIMED_WAITING:计时等待

- TERMINATED:终止状态

3. 创建线程方式

```java

// 继承Thread类

class MyThread extends Thread {

public void run() {

System.out.println(线程执行);

}

}

// 实现Runnable接口

class MyRunnable implements Runnable {

public void run() {

System.out.println(Runnable执行);

}

}

// 使用Lambda表达式

Thread lambdaThread = new Thread(() -> System.out.println(Lambda线程));

```

#### 二、线程同步与通信

1. synchronized关键字

```java

// 同步方法

public synchronized void syncMethod() {

// 临界区代码

}

// 同步代码块

public void syncBlock() {

synchronized(this) {

// 临界区代码

}

}

// 静态同步方法

public static synchronized void staticSync() {

// 类级别同步

}

```

2. Lock接口

```java

ReentrantLock lock = new ReentrantLock();

public void lockExample() {

lock.lock();

try {

// 临界区代码

} finally {

lock.unlock();

}

}

```

3. volatile关键字

```java

private volatile boolean flag = false;

// 保证可见性,不保证原子性

```

4. 等待/通知机制

```java

// 生产者-消费者模式示例

class Buffer {

private Queue queue = new LinkedList<>();

private int capacity;

public synchronized void produce(int item) throws InterruptedException {

while (queue.size() == capacity) {

wait();

}

queue.offer(item);

notifyAll();

}

public synchronized int consume() throws InterruptedException {

while (queue.isEmpty()) {

wait();

}

int item = queue.poll();

notifyAll();

return item;

}

}

```

#### 三、Java并发工具类

1. CountDownLatch

```java

CountDownLatch latch = new CountDownLatch(3);

// 多个线程完成后继续执行

latch.countDown();

latch.await();

```

2. CyclicBarrier

```java

CyclicBarrier barrier = new CyclicBarrier(3,

() -> System.out.println(所有线程到达屏障));

```

3. Semaphore

```java

Semaphore semaphore = new Semaphore(5);

semaphore.acquire();

// 访问共享资源

semaphore.release();

```

4. Exchanger

```java

Exchanger exchanger = new Exchanger<>();

// 两个线程间交换数据

```

#### 四、线程池与Executor框架

1. 线程池创建

```java

// 固定大小线程池

ExecutorService fixedPool = Executors.newFixedThreadPool(10);

// 缓存线程池

ExecutorService cachedPool = Executors.newCachedThreadPool();

// 定时线程池

ScheduledExecutorService scheduledPool =

Executors.newScheduledThreadPool(5);

// 自定义线程池

ThreadPoolExecutor customPool = new ThreadPoolExecutor(

5, 10, 60L, TimeUnit.SECONDS,

new ArrayBlockingQueue<>(100)

);

```

2. Future与Callable

```java

Callable task = () -> {

Thread.sleep(1000);

return 42;

};

Future future = executor.submit(task);

Integer result = future.get(); // 阻塞获取结果

```

3. CompletableFuture

```java

CompletableFuture.supplyAsync(() -> Hello)

.thenApply(s -> s + World)

.thenAccept(System.out::println)

.exceptionally(ex -> {

System.out.println(错误处理);

return null;

});

```

#### 五、高级并发特性

1. 原子操作类

```java

AtomicInteger atomicInt = new AtomicInteger(0);

atomicInt.incrementAndGet();

atomicInt.compareAndSet(1, 2); // CAS操作

```

2. 并发集合

```java

ConcurrentHashMap concurrentMap =

new ConcurrentHashMap<>();

CopyOnWriteArrayList copyOnWriteList =

new CopyOnWriteArrayList<>();

BlockingQueue blockingQueue =

new LinkedBlockingQueue<>();

```

3. ThreadLocal

```java

ThreadLocal dateFormat =

ThreadLocal.withInitial(() -> new SimpleDateFormat(yyyy-MM-dd));

```

#### 六、性能优化与最佳实践

1. 避免死锁

```java

// 按固定顺序获取锁

public void transfer(Account from, Account to, int amount) {

Object firstLock = from.hashCode() < to.hashCode() ? from : to;

Object secondLock = from.hashCode() < to.hashCode() ? to : from;

synchronized(firstLock) {

synchronized(secondLock) {

// 转账操作

}

}

}

```

2. 减少锁竞争

- 使用细粒度锁

- 采用读写锁(ReentrantReadWriteLock)

- 使用无锁数据结构

3. 线程池调优

- 根据任务类型选择合适线程池

- 合理设置核心线程数和最大线程数

- 使用合适的阻塞队列

#### 七、实际应用场景

1. Web服务器并发处理

2. 数据库连接池管理

3. 消息队列消费者

4. 批量数据处理

5. 实时数据采集与处理

#### 八、常见问题与解决方案

1. 内存可见性问题:使用volatile或synchronized

2. 竞态条件:使用原子操作或同步机制

3. 线程饥饿:公平锁或调整线程优先级

4. 活锁:引入随机退避机制

5. 资源泄漏:确保正确释放资源

通过深入理解Java多线程编程的各个层面,从基础概念到高级实践,开发者能够构建出高效、稳定的并发应用程序。在实际开发中,需要根据具体场景选择合适的并发策略,平衡性能与复杂度,确保程序的正确性和可靠性。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐