JUC专题

作者: 阔阔飞翔 | 来源:发表于2019-01-22 16:37 被阅读0次

1、倒计时锁--CountDownLatch
可实现线程安全的计数,例如下面代码,执行countDownLatch.countDown()就会线程安全的计数,直到循环结束才会输出finish,可用于计算最后结果

@Slf4j
public class CountDownLatchExample1 {

    private final static int threadCount = 200;

    public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    System.out.println(e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("finish");
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(100);
        System.out.println("{}"+threadNum);
        Thread.sleep(100);
    }
}

2、信号量--Semaphore
可控制并发数量,
···
@Slf4j
public class SemaphoreExample1 {

private final static int threadCount = 20;

public static void main(String[] args) throws Exception {

    ExecutorService exec = Executors.newCachedThreadPool();

    final Semaphore semaphore = new Semaphore(3);

    for (int i = 0; i < threadCount; i++) {
        final int threadNum = i;
        exec.execute(() -> {
            try {
                semaphore.acquire(); // 获取一个许可
                test(threadNum);
                semaphore.release(); // 释放一个许可
            } catch (Exception e) {
                log.error("exception", e);
            }
        });
    }
    exec.shutdown();
}

private static void test(int threadNum) throws Exception {
    log.info("{}", threadNum);
    Thread.sleep(1000);
}

}
···
3、屏障--CyclicBarrier
必须有几个线程准备好以后才能执行,可用于秒杀,抢票等

相关文章

网友评论

      本文标题:JUC专题

      本文链接:https://www.haomeiwen.com/subject/iwqrjqtx.html