JUC详细介绍

JUC(Java Util Concurrent)是Java 5.0引入的一个并发工具包,位于`java.util.concurrent`包及其子包中,旨在简化多线程编程,提供高效且易于使用的并发工具。以下是JUC的核心功能模块及常用类的详细介绍:


### **1. 线程池(Executor框架)**
线程池管理线程生命周期,避免频繁创建/销毁线程的开销,提高性能。

**核心接口与类:**
- **Executor**:线程池的基础接口,定义`execute(Runnable)`方法。
- **ExecutorService**:扩展`Executor`,提供管理线程池生命周期的方法(如`shutdown()`、`submit()`)。
- **ThreadPoolExecutor**:标准线程池实现,支持自定义线程数量、队列策略等。
- **ScheduledExecutorService**:支持定时/周期性任务执行。
- **Executors**:工具类,提供创建线程池的静态工厂方法(如`newFixedThreadPool`、`newCachedThreadPool`)。

**示例:**
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        // 提交任务
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println("Task " + taskId + " executed by " + Thread.currentThread().getName());
            });
        }
        
        // 关闭线程池
        executor.shutdown();
    }
}
```


### **2. 原子类(Atomic包)**
基于CAS(Compare-and-Swap)无锁算法实现原子操作,避免同步开销。

**常用类:**
- `AtomicInteger`、`AtomicLong`、`AtomicBoolean`:原子更新基本类型。
- `AtomicReference`:原子更新引用类型。
- `AtomicIntegerArray`、`AtomicReferenceArray`:原子更新数组元素。
- `AtomicStampedReference`:解决ABA问题(通过版本号)。

**示例:**
```java
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.incrementAndGet(); // 原子自增
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.incrementAndGet();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Counter: " + counter.get()); // 输出2000,无竞争问题
    }
}
```


### **3. 锁机制(Lock接口)**
提供比`synchronized`更灵活的锁控制,支持公平锁、可重入锁、条件变量等。

**核心类:**
- **ReentrantLock**:可重入锁,支持公平/非公平模式。
- **ReentrantReadWriteLock**:读写锁,允许多个读线程或单个写线程访问。
- **StampedLock**:支持乐观读锁,性能更优。

**示例:**
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private final Lock lock = new ReentrantLock();
    private int count = 0;

    public void increment() {
        lock.lock(); // 获取锁
        try {
            count++;
        } finally {
            lock.unlock(); // 释放锁
        }
    }
}
```


### **4. 并发容器**
提供线程安全且高效的集合类,替代`Collections.synchronizedXXX()`包装的传统容器。

**常用类:**
- **ConcurrentHashMap**:线程安全的哈希表,采用分段锁或CAS实现高效并发。
- **CopyOnWriteArrayList**:写时复制的列表,适用于读多写少场景。
- **ConcurrentLinkedQueue**:无界线程安全队列,基于链表实现。
- **BlockingQueue**:阻塞队列接口,实现类包括`ArrayBlockingQueue`、`LinkedBlockingQueue`、`PriorityBlockingQueue`等,支持生产-消费模式。

**示例:**
```java
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        // 线程安全的put和get操作
        map.put("key1", 1);
        map.put("key2", 2);
        
        System.out.println(map.get("key1")); // 输出1
    }
}
```


### **5. 同步工具类**
提供线程间协作的工具,如倒计时、屏障、信号量等。

**核心类:**
- **CountDownLatch**:倒计时锁存器,允许一个或多个线程等待其他线程完成操作。
- **CyclicBarrier**:循环屏障,多个线程相互等待到达共同屏障点后继续执行。
- **Semaphore**:信号量,控制同时访问资源的线程数量。
- **Exchanger**:交换器,允许两个线程交换数据。

**示例(CountDownLatch):**
```java
import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        for (int i = 0; i < 3; i++) {
            final int workerId = i;
            new Thread(() -> {
                System.out.println("Worker " + workerId + " started");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Worker " + workerId + " finished");
                latch.countDown(); // 倒计时减1
            }).start();
        }

        latch.await(); // 等待所有工作线程完成
        System.out.println("All workers finished");
    }
}
```


### **6. 并发工具类**
提供高级并发功能,如Future、CompletableFuture等。

**核心类:**
- **Future**:表示异步计算的结果,通过`ExecutorService.submit()`返回。
- **CompletableFuture**:增强版Future,支持链式调用、组合操作和回调函数。
- **ForkJoinPool**:分治任务框架,适用于大规模并行计算(如递归任务拆分)。

**示例(CompletableFuture):**
```java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 异步执行任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Result";
        });

        // 任务完成后执行回调
        future.thenAccept(result -> System.out.println("Received: " + result));

        // 获取结果(阻塞)
        System.out.println(future.get()); // 输出"Result"
    }
}
```


### **总结**
JUC通过提供线程池、原子类、锁机制、并发容器和同步工具类,大大简化了Java多线程编程,减少了手动管理线程的复杂度,并提高了并发性能。合理使用JUC可以有效避免线程安全问题,提升程序的可靠性和吞吐量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾修行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值