java线程协作 - 并发工具类

并发工具类

  • CountDownLacth
  • Semaphore
  • CyclicBarrier

CountDownLacth
CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有框架服务之后执行。

public class CountDownLatchExample {

    private final  static int threadCount = 200;
    
    public static void main(String[] arg) {
    
        ExecutorService exec = Executors.newCachedThreadPool(); 
        
        final CountDownLatch lacth = new CountDownLatch(5);
        
        for (int i = 0; i < 5; i++) {
            exec.execute( () -> {
            final int threadNum  = i;
            try {
                test(threadNum);
            } catch (Exception e) {
                log.error("exception", e);
            } finally {
                // latch递减
                lacth.countDown();
            }
            });
        }
        // 等待latch计数器为0,则继续往下执行
        latch.await();
        // latch的await方法也可以传入等待时间,等到等待时间后不管有没完成计数都往下执行
        // latch.await( 10, TimeUnit.MILLISECONDS);
        log.info("finished");
        exec.shutdown();
    }

    public static void test(int i)  throw Exception{
        log.info("thread: {}", i);
    }
}

Semaphore
主要用来控制并发访问特定资源的线程数量,协调各个线程合理使用公共资源。

public class SemaphoreExample {

    private final  static int threadCount = 200;
    public static void main(String[] arg) {
        ExecutorService exec = Executors.newCachedThreadPool(); 
    
        final Semaphore semaphore = new Semaphore(3);
    
        for (int i = 0; i < threadCount; i++) {
            exec.excute( () )-> {
            final int threadNum  = i;
            try {
                // tryAcquire会尝试去获取一个信号量,如果获取不到
                // 则什么都不会发生,走接下来的逻辑
                // if (semaphore.tryAcquire(1)) {
                //    test(i);
                //    semaphore.release();//释放一个信号量
                // }
                semaphore.acquire();//获取一个信号量
                test(i);
                semaphore.release();//释放一个信号量
            } catch (Exception e) {
                log.error("exception", e);
            } 
            });
        }
        log.info("finished");
        exec.shutdown();
    }
    
    public static void test(int i)  throw Exception{
        log.info("thread: {}", i);
    }
}

CyclicBarrier
一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。

public class CyclicBarrierExample {

    private final  static int threadCount = 200;
    
    private final static CyclicBarrier cyclicBarrier = new CyclicBarrier(7, 
        () -> {
        log.info("callback is running !");
        }
    );
    
    public static void main(String[] arg) {
    
        ExecutorService exec = Executors.newCachedThreadPool(); 
        
        for (int i = 0; i < threadCount; i++) {
            exec.excute( () -> {
                final int threadNum  = i;
                try {
                    race(i);
                } catch (Exception e) {
                    log.error("exception", e);
                } 
            });
        }
        log.info("finished");
        
        exec.shutdown();
    }
    
    public static void race(int i)  throw Exception{
        log.info("thread {} is ready", i);
        cyclicBarrier.await();
        log.info("thread {} is continue", i);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值