### Java多线程编程实践:从基础到高级应用

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

1. 线程与进程

- 进程是操作系统资源分配的基本单位

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

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

2. 线程创建方式

```java

// 继承Thread类

class MyThread extends Thread {

@Override

public void run() {

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

}

}

// 实现Runnable接口

class MyRunnable implements Runnable {

@Override

public void run() {

System.out.println(Runnable执行);

}

}

// 使用Lambda表达式

Thread lambdaThread = new Thread(() -> {

System.out.println(Lambda线程);

});

```

#### 二、线程生命周期与管理

1. 线程状态

- NEW:新建状态

- RUNNABLE:可运行状态

- BLOCKED:阻塞状态

- WAITING:等待状态

- TIMED_WAITING:超时等待

- TERMINATED:终止状态

2. 线程控制方法

```java

// 线程休眠

Thread.sleep(1000);

// 线程等待

thread.join();

// 线程中断

thread.interrupt();

```

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

1. synchronized关键字

```java

// 同步方法

public synchronized void syncMethod() {

// 临界区代码

}

// 同步代码块

public void syncBlock() {

synchronized(this) {

// 临界区代码

}

}

```

2. Lock接口

```java

ReentrantLock lock = new ReentrantLock();

public void lockMethod() {

lock.lock();

try {

// 临界区代码

} finally {

lock.unlock();

}

}

```

3. 等待通知机制

```java

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

class Buffer {

private final Queue queue = new LinkedList<>();

private final int capacity;

public Buffer(int capacity) {

this.capacity = 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;

}

}

```

#### 四、并发工具类

1. CountDownLatch

```java

CountDownLatch latch = new CountDownLatch(3);

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

for (int i = 0; i < 3; i++) {

new Thread(() -> {

// 执行任务

latch.countDown();

}).start();

}

latch.await(); // 等待所有线程完成

```

2. CyclicBarrier

```java

CyclicBarrier barrier = new CyclicBarrier(3,

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

for (int i = 0; i < 3; i++) {

new Thread(() -> {

// 执行任务

barrier.await(); // 等待其他线程

}).start();

}

```

3. Semaphore

```java

Semaphore semaphore = new Semaphore(3); // 限制并发数

public void accessResource() throws InterruptedException {

semaphore.acquire();

try {

// 访问共享资源

} finally {

semaphore.release();

}

}

```

#### 五、线程池技术

1. 线程池创建

```java

// 使用Executors工厂类

ExecutorService fixedPool = Executors.newFixedThreadPool(10);

ExecutorService cachedPool = Executors.newCachedThreadPool();

ExecutorService scheduledPool = Executors.newScheduledThreadPool(5);

// 自定义线程池

ThreadPoolExecutor customPool = new ThreadPoolExecutor(

5, // 核心线程数

10, // 最大线程数

60, // 空闲时间

TimeUnit.SECONDS, // 时间单位

new ArrayBlockingQueue<>(100) // 工作队列

);

```

2. 线程池任务执行

```java

// 提交任务

Future future = executor.submit(() -> {

// 执行任务

return 任务结果;

});

// 获取结果

String result = future.get();

```

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

1. CompletableFuture

```java

// 异步编程

CompletableFuture.supplyAsync(() -> {

// 异步执行任务

return 结果;

}).thenApply(result -> {

// 处理结果

return result + 处理;

}).thenAccept(finalResult -> {

// 消费最终结果

System.out.println(finalResult);

});

```

2. 原子操作类

```java

AtomicInteger counter = new AtomicInteger(0);

counter.incrementAndGet(); // 原子自增

counter.compareAndSet(expect, update); // CAS操作

```

3. 并发集合

```java

ConcurrentHashMap map = new ConcurrentHashMap<>();

CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();

BlockingQueue queue = new LinkedBlockingQueue<>();

```

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

1. 避免死锁

- 按固定顺序获取锁

- 使用tryLock()设置超时时间

- 避免嵌套锁

2. 减少锁竞争

- 使用细粒度锁

- 采用无锁编程

- 使用读写锁

3. 资源管理

- 及时关闭线程池

- 合理设置线程池参数

- 使用ThreadLocal避免共享

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

1. Web服务器并发处理

```java

// 使用线程池处理HTTP请求

ExecutorService requestHandler = Executors.newFixedThreadPool(100);

while (true) {

Socket client = serverSocket.accept();

requestHandler.submit(() -> handleRequest(client));

}

```

2. 批量数据处理

```java

// 并行处理大数据集

List dataList = getLargeDataSet();

List> futures = dataList.stream()

.map(data -> CompletableFuture.supplyAsync(() -> process(data), executor))

.collect(Collectors.toList());

List results = futures.stream()

.map(CompletableFuture::join)

.collect(Collectors.toList());

```

3. 定时任务调度

```java

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

scheduler.scheduleAtFixedRate(() -> {

// 执行定时任务

}, 0, 1, TimeUnit.HOURS);

```

通过系统学习Java多线程编程,从基础概念到高级应用,开发者能够构建高效、可靠的并发系统。掌握线程同步、线程池管理、并发工具等关键技术,结合具体业务场景合理应用,可以显著提升程序性能和用户体验。

Logo

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

更多推荐