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

#### 一、线程基础与创建方式

1. 继承Thread类

通过扩展Thread类并重写run()方法实现多线程:

```java

class MyThread extends Thread {

@Override

public void run() {

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

}

}

// 启动线程

new MyThread().start();

```

2. 实现Runnable接口

更推荐的方式,避免单继承限制:

```java

class MyRunnable implements Runnable {

@Override

public void run() {

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

}

}

// 使用Thread包装

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

```

3. 实现Callable接口

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

```java

class MyCallable implements Callable {

@Override

public String call() throws Exception {

return Callable执行结果;

}

}

// 通过FutureTask获取结果

FutureTask task = new FutureTask<>(new MyCallable());

new Thread(task).start();

System.out.println(task.get());

```

#### 二、线程同步与锁机制

1. synchronized关键字

- 同步代码块:

```java

private final Object lock = new Object();

public void syncMethod() {

synchronized(lock) {

// 临界区代码

}

}

```

- 同步方法:

```java

public synchronized void increment() {

// 原子操作

}

```

2. ReentrantLock可重入锁

提供更灵活的锁控制:

```java

private final ReentrantLock lock = new ReentrantLock();

public void performTask() {

lock.lock();

try {

// 受保护的代码

} finally {

lock.unlock();

}

}

```

3. 读写锁(ReadWriteLock)

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

```java

private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

public void readData() {

rwLock.readLock().lock();

try {

// 读操作

} finally {

rwLock.readLock().unlock();

}

}

```

#### 三、线程间通信

1. wait/notify机制

```java

class SharedResource {

private boolean available = false;

public synchronized void produce() throws InterruptedException {

while(available) wait();

// 生产资源

available = true;

notifyAll();

}

public synchronized void consume() throws InterruptedException {

while(!available) wait();

// 消费资源

available = false;

notifyAll();

}

}

```

2. Condition条件变量

```java

class BoundedBuffer {

private final Lock lock = new ReentrantLock();

private final Condition notFull = lock.newCondition();

private final Condition notEmpty = lock.newCondition();

public void put(Object x) throws InterruptedException {

lock.lock();

try {

while(count == items.length)

notFull.await();

// 放入元素

notEmpty.signal();

} finally {

lock.unlock();

}

}

}

```

#### 四、并发工具类

1. CountDownLatch

```java

CountDownLatch latch = new CountDownLatch(3);

// 多个线程

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(5); // 允许5个并发

semaphore.acquire();

try {

// 访问共享资源

} finally {

semaphore.release();

}

```

#### 五、线程池技术

1. Executor框架

```java

ExecutorService executor = Executors.newFixedThreadPool(10);

// 提交任务

Future future = executor.submit(() -> 任务结果);

// 关闭线程池

executor.shutdown();

```

2. ThreadPoolExecutor定制

```java

ThreadPoolExecutor executor = new ThreadPoolExecutor(

5, // 核心线程数

10, // 最大线程数

60L, TimeUnit.SECONDS, // 空闲时间

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

);

```

#### 六、原子操作类

```java

AtomicInteger counter = new AtomicInteger(0);

// 原子递增

counter.incrementAndGet();

// CAS操作

counter.compareAndSet(expect, update);

```

#### 七、并发集合

1. ConcurrentHashMap

```java

ConcurrentHashMap map = new ConcurrentHashMap<>();

map.put(key, value);

map.get(key);

```

2. CopyOnWriteArrayList

```java

CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();

list.add(element);

```

#### 八、最佳实践与注意事项

1. 避免死锁:按固定顺序获取锁

2. 减少锁粒度:使用分段锁或读写锁

3. 避免长时间持有锁

4. 使用线程局部变量:ThreadLocal

5. 合理设置线程池参数

6. 及时关闭资源

7. 异常处理:UncaughtExceptionHandler

通过深入理解这些核心技术并结合实际场景进行实践,能够构建出高效、稳定的多线程Java应用程序。

Logo

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

更多推荐