J.U.C之AQS

J.U.C之AQS

AbstractQueuedSynhronizer

底层双向链表队列的一种实现

使用Node实现FIFO队列,可以用于构建锁或者其他同步装置的基础框架

利用了一个int类型表示状态

使用方法继承,设计是使用模版方法,子类通过继承并通过实现他的方法来管理其状态{acquire 和 release}的方法操纵状态

可以同时实现拍他锁和共享锁模式(独占、共享)

AQS同步组件

CountDownLatch,闭锁,通过一个计数来保证线程是否需要一直阻塞

private static final int threadCount=200;

public static void main(String[] args) throws InterruptedException {
   
    ExecutorService executorService =
            Executors.newCachedThreadPool();
    final CountDownLatch downLatch=new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; i++) {
   
        final int count=i;
        executorService.execute(()->{
   
            try
            {
   
                test(count);
            }catch(Exception ex){
   
                log.info("{}",ex.getMessage());
            }finally{
   
                downLatch.countDown();
            }
        });
    }
    downLatch.await();
    log.info("{}","fistish");
    executorService.shutdown();
}

private static void test(int i){
   
    try {
   
        Thread.sleep(100);
        log.info("{}",i);
    } catch (InterruptedException e) {
   
        e.printStackTrace();
    }
}

注:主要方法countDown、await,await函数需要等待countDown计数为0,才继续执行,调用线程池,用完了需要关闭showDown是需要等到当前给定线程继续执行完才能继续执行,downLatch.await(10, TimeUnit.MILLISECONDS);添加等待时间

Semaphore:控制同一时间并发线程数目,信号量,并发访问控制

        final Semaphore semaphore=new Semaphore(3);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCuont; i++) {
   
            final int count=i;
            executorService.execute(()->{
   
                try {
   
                    if(semaphore.tryAcquire(1000, TimeUnit.MILLISECONDS)){
   
//                        semaphore.acquire(3);
                        test(count);
                        semaphore.release(3);
                    }
                } catch (InterruptedException e) {
   
                    e.printStackTrace
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值