3月7日java学习笔记

一、线程通信与协作

  1. wait()与notify()机制
    作用:实现线程间条件等待与唤醒(必须在同步代码块中使用)

经典示例(生产者-消费者模型):

class Buffer {
private Queue queue = new LinkedList<>();
private int capacity = 2;

public synchronized void produce(int item) throws InterruptedException {
    while (queue.size() == capacity) {
        wait(); // 缓冲区满,生产者等待
    }
    queue.add(item);
    notifyAll(); // 唤醒消费者线程
}

public synchronized int consume() throws InterruptedException {
    while (queue.isEmpty()) {
        wait(); // 缓冲区空,消费者等待
    }
    int item = queue.poll();
    notifyAll(); // 唤醒生产者线程
    return item;
}

}
二、并发工具类

  1. CountDownLatch
    用途:等待多个线程完成任务后再继续主线程

CountDownLatch latch = new CountDownLatch(3);
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
pool.submit(() -> {
// 执行任务
latch.countDown();
});
}
latch.await(); // 等待所有任务完成
System.out.println("所有任务完成");
pool.shutdown();
2. CyclicBarrier
用途:多线程相互等待至屏障点后继续

CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("所有线程到达屏障");
});
for (int i = 0; i < 3; i++) {
new Thread(() -> {
// 执行任务
barrier.await(); // 等待其他线程
}).start();
}
3. ConcurrentHashMap
特性:线程安全的哈希表(分段锁优化)

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 100);
map.computeIfAbsent("name", k -> k.length()); // 原子操作

posted @ 2025-03-13 22:12  头发少的文不识  阅读(18)  评论(0)    收藏  举报