Java多线程-3-并发容器和工具类

三、并发容器和工具类

1、并发容器

【1】ConcurrentHashMap

多线程情况下的HashMap。注意KEY和VALUE都不能为null

【2】ConcurrentSkipListMap

多线程情况下的TreeMap

ConcurrentSkipListMap<String, Integer> concurrentSkipListMap = new ConcurrentSkipListMap<String, Integer>();
concurrentSkipListMap.put("a", 1);
concurrentSkipListMap.put("A", 2);
concurrentSkipListMap.put("0", 3);
concurrentSkipListMap.put("b", 4);
System.out.println(concurrentSkipListMap); // {0=3, A=2, a=1, b=4}

System.out.println("0-" + (int)'0'); // 0-48
System.out.println("A-" + (int)'A'); // A-65
System.out.println("a-" + (int)'a'); // a-97
System.out.println("b-" + (int)'b'); // b-98

【3】ConcurrentSkipListSet

多线程情况下的TreeSet

【4】CopyOnWriteArrayList

多线程情况下的ArrayList。对写操作加锁,读操作没有加锁,保证了性能

volatile修饰的Object数组,当每次对数组进行修改时,会创建新的数组,并将引用指向它

例如add操作:

public boolean add(E e) {
    
    
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
    
    
        Object[] elements = getArray();
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len + 1); // 创建新的数组
        newElements[len] = e;
        setArray(newElements); // 指向新的数组
        return true;
    } finally {
    
    
        lock.unlock();
    }
}

【5】CopyOnWriteArraySet

内部维护了一个CopyOnWriteArrayList

private final CopyOnWriteArrayList<E> al;

在添加新的元素前,会先判断是否已经存在该元素,如果没有找到,才会保存到容器里

/**
 * java.util.concurrent.CopyOnWriteArrayList#addIfAbsent(E)方法
 */
public boolean addIfAbsent(E e) {
    
    
    Object[] snapshot = getArray();
    return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
    addIfAbsent(e, snapshot);
}

2、并发工具类

【1】CountDownLatch

倒计时闩锁。事先给出统计数值,每次减1,当减到0时,放行

CountDownLatch countDownLatch = new CountDownLatch(2);

new Thread(() -> {
    
    
    System.out.println("A");
    try {
    
    
        Thread.sleep(500);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
    countDownLatch.countDown(); // 减1
}).start();

new Thread(() -> {
    
    
    System.out.println("B");
    try {
    
    
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
    countDownLatch.countDown(); // 减1
}).start();

try {
    
    
    countDownLatch.await(); // Main线程等待
} catch (InterruptedException e) {
    
    
    e.printStackTrace();
}

System.out.println("结束!");

【2】CyclicBarrier

循环屏障。事先给出统计数值,每次加1,当加到统计数值时,放行

使用方式一:

public static void main(String[] args) {
    
    
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3); // 记得算上Main线程

    new Thread(() -> {
    
    
        System.out.println("A");
        try {
    
    
            Thread.sleep(500);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        try {
    
    
            cyclicBarrier.await(); // 等待(加1)
        } catch (InterruptedException | BrokenBarrierException e) {
    
    
            e.printStackTrace();
        }
    }).start();

    new Thread(() -> {
    
    
        System.out.println("B");
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        try {
    
    
            cyclicBarrier.await(); // 等待(加1)
        } catch (InterruptedException | BrokenBarrierException e) {
    
    
            e.printStackTrace();
        }
    }).start();

    try {
    
    
        cyclicBarrier.await(2, TimeUnit.SECONDS); // 只等待2秒钟(加1)
    } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
    
    
        e.printStackTrace();
    }

    System.out.println("结束!");
}

使用方式二:

CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
    
    
    System.out.println("结束!");
}); // 其他线程都执行完毕后,执行该线程方法

new Thread(() -> {
    
    
    System.out.println("A");
    try {
    
    
        Thread.sleep(500);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
    try {
    
    
        cyclicBarrier.await(); // 等待(加1)
    } catch (InterruptedException | BrokenBarrierException e) {
    
    
        e.printStackTrace();
    }
}).start();

new Thread(() -> {
    
    
    System.out.println("B");
    try {
    
    
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
    try {
    
    
        cyclicBarrier.await(); // 等待(加1)
    } catch (InterruptedException | BrokenBarrierException e) {
    
    
        e.printStackTrace();
    }
}).start();

【3】Semaphore

信号量。指定一次只允许执行的线程个数

int loop = 10;
int permits = 2;

ExecutorService executorService = Executors.newFixedThreadPool(loop);
Semaphore semaphore = new Semaphore(permits);

for (int i = 0; i < loop; i++) {
    
    
    executorService.execute(() -> {
    
    
        try {
    
    
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " ---> 执行任务");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            semaphore.release();
        }
    });
}

if (!executorService.isShutdown()) {
    
    
    executorService.shutdown();
}

【4】Exchanger

交换者。用于线程间的数据交换。如果有一个线程发起了交换,则会一直等待另外一线程执行交换。如果怕等待时间过长,则可以使用public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException方法

Exchanger<String> exchanger = new Exchanger<String>();
new Thread(() -> {
    
    
    try {
    
    
        System.out.println(Thread.currentThread().getName() + "发出了消息,等待回复");

        String exchange = exchanger.exchange("hello?");
        Thread.sleep(2000);
        System.out.println(Thread.currentThread().getName() + "收到了:" + exchange);
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
}, "线程A").start();

new Thread(() -> {
    
    
    try {
    
    
        Thread.sleep(3000);

        String exchange = exchanger.exchange("hi!");
        System.out.println(Thread.currentThread().getName() + "收到了:" + exchange + ",并且已回复");
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
}, "线程B").start();

猜你喜欢

转载自blog.csdn.net/adsl624153/article/details/103865261