# Java多线程编程的核心技术与实践应用

## 线程创建与管理

### 继承Thread类

通过继承Thread类并重写run方法创建线程:

```java

class MyThread extends Thread {

@Override

public void run() {

System.out.println(线程执行: + Thread.currentThread().getName());

}

}

// 使用示例

MyThread thread = new MyThread();

thread.start();

```

### 实现Runnable接口

更推荐的线程创建方式,避免单继承限制:

```java

class MyRunnable implements Runnable {

@Override

public void run() {

System.out.println(Runnable线程执行: + Thread.currentThread().getName());

}

}

// 使用示例

Thread thread = new Thread(new MyRunnable());

thread.start();

```

### 实现Callable接口

支持返回结果和抛出异常的线程创建方式:

```java

class MyCallable implements Callable {

@Override

public String call() throws Exception {

return Callable执行结果;

}

}

// 使用示例

ExecutorService executor = Executors.newSingleThreadExecutor();

Future future = executor.submit(new MyCallable());

String result = future.get();

executor.shutdown();

```

## 线程同步机制

### synchronized关键字

保证方法或代码块的线程安全:

```java

class Counter {

private int count = 0;

// 同步方法

public synchronized void increment() {

count++;

}

// 同步代码块

public void decrement() {

synchronized(this) {

count--;

}

}

}

```

### ReentrantLock可重入锁

提供更灵活的锁机制:

```java

class SafeCounter {

private final ReentrantLock lock = new ReentrantLock();

private int count = 0;

public void increment() {

lock.lock();

try {

count++;

} finally {

lock.unlock();

}

}

}

```

### 读写锁

提高读多写少场景的性能:

```java

class ReadWriteCounter {

private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

private int value = 0;

public int getValue() {

rwLock.readLock().lock();

try {

return value;

} finally {

rwLock.readLock().unlock();

}

}

public void setValue(int newValue) {

rwLock.writeLock().lock();

try {

value = newValue;

} finally {

rwLock.writeLock().unlock();

}

}

}

```

## 线程间通信

### wait/notify机制

实现线程间的协调与通信:

```java

class MessageQueue {

private String message;

private boolean empty = true;

public synchronized String take() throws InterruptedException {

while (empty) {

wait();

}

empty = true;

notifyAll();

return message;

}

public synchronized void put(String message) throws InterruptedException {

while (!empty) {

wait();

}

empty = false;

this.message = message;

notifyAll();

}

}

```

### BlockingQueue阻塞队列

线程安全的队列实现:

```java

BlockingQueue queue = new LinkedBlockingQueue<>(10);

// 生产者线程

new Thread(() -> {

try {

queue.put(消息);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}).start();

// 消费者线程

new Thread(() -> {

try {

String message = queue.take();

System.out.println(收到: + message);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}).start();

```

## 线程池技术

### 线程池创建与配置

```java

// 固定大小线程池

ExecutorService fixedPool = Executors.newFixedThreadPool(5);

// 缓存线程池

ExecutorService cachedPool = Executors.newCachedThreadPool();

// 定时任务线程池

ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(3);

// 自定义线程池

ThreadPoolExecutor customPool = new ThreadPoolExecutor(

2, // 核心线程数

10, // 最大线程数

60L, // 空闲线程存活时间

TimeUnit.SECONDS, // 时间单位

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

);

```

### CompletableFuture异步编程

简化异步任务处理:

```java

CompletableFuture.supplyAsync(() -> {

// 异步执行任务

return 任务结果;

}).thenApply(result -> {

// 处理结果

return result + 已处理;

}).thenAccept(finalResult -> {

// 消费最终结果

System.out.println(finalResult);

}).exceptionally(ex -> {

// 异常处理

System.out.println(执行失败: + ex.getMessage());

return null;

});

```

## 原子操作类

### 基本类型原子类

```java

AtomicInteger atomicInt = new AtomicInteger(0);

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

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

AtomicLong atomicLong = new AtomicLong();

AtomicBoolean atomicBoolean = new AtomicBoolean();

```

### 引用类型原子类

```java

AtomicReference atomicRef = new AtomicReference<>(初始值);

atomicRef.compareAndSet(初始值, 新值);

// 原子更新器

AtomicIntegerFieldUpdater updater =

AtomicIntegerFieldUpdater.newUpdater(MyClass.class, fieldName);

```

## 并发集合类

### ConcurrentHashMap

线程安全的哈希表:

```java

ConcurrentHashMap map = new ConcurrentHashMap<>();

map.put(key, 1);

map.computeIfAbsent(key, k -> 0); // 原子操作

// 并行遍历

map.forEach(2, (k, v) -> System.out.println(k + : + v));

```

### CopyOnWriteArrayList

写时复制的线程安全列表:

```java

CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();

list.add(元素);

// 遍历时不需要同步,因为内部会复制数组

for (String item : list) {

System.out.println(item);

}

```

## 实践应用场景

### 生产者-消费者模式

```java

class ProducerConsumer {

private final BlockingQueue queue = new LinkedBlockingQueue<>(10);

class Producer implements Runnable {

public void run() {

try {

int value = 0;

while (true) {

queue.put(value);

System.out.println(生产: + value);

value++;

Thread.sleep(100);

}

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}

}

class Consumer implements Runnable {

public void run() {

try {

while (true) {

Integer value = queue.take();

System.out.println(消费: + value);

Thread.sleep(150);

}

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}

}

}

}

```

### 并行任务处理

```java

class ParallelProcessor {

private final ExecutorService executor = Executors.newFixedThreadPool(4);

public List processInParallel(List> tasks)

throws InterruptedException {

List> futures = executor.invokeAll(tasks);

List results = new ArrayList<>();

for (Future future : futures) {

try {

results.add(future.get());

} catch (ExecutionException e) {

// 处理异常

}

}

return results;

}

}

```

## 性能优化与最佳实践

### 避免死锁

```java

class DeadlockPrevention {

private final Object lock1 = new Object();

private final Object lock2 = new Object();

public void method1() {

synchronized (lock1) {

synchronized (lock2) {

// 操作

}

}

}

public void method2() {

synchronized (lock1) { // 保持相同的锁顺序

synchronized (lock2) {

// 操作

}

}

}

}

```

### 线程局部变量

```java

class ThreadLocalExample {

private static final ThreadLocal dateFormat =

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

public String formatDate(Date date) {

return dateFormat.get().format(date);

}

}

```

Java多线程编程的核心在于理解线程生命周期、同步机制和并发工具类的正确使用。通过合理选择线程创建方式、使用适当的同步机制、充分利用线程池和并发集合,可以构建出高效、稳定的并发应用程序。在实际开发中,还需要注意避免常见的并发问题,如死锁、竞态条件和内存可见性问题,确保程序的正确性和性能。

Logo

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

更多推荐