AQS原理应用(一):CountDownLatch的典型用法和实现原理

一、基本概念

CountDownLatch :倒计时器,是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。

二、CountDownLatch 的三种典型用法

  • 某一线程在开始运行前等待 n 个线程执行完毕。
  • 实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。
  • 死锁的检测
(1) 某一线程在开始运行前等待 n 个线程执行完毕。

将 CountDownLatch 的计数器初始化为 n :new CountDownLatch(n),每当一个任务线程执行完毕,就将计数器减 1 countdownlatch.countDown(),当计数器的值变为 0 时,在CountDownLatch上 await() 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。

情况①:设定遍历次数、核心线程数 countdownLatch都为size时,直到等待所有核心线程都执行完成后,再调用主线程的代码

public class CountDownLatchTest {

  private static final int size = 8;

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(size);
    CountDownLatch countDownLatch = new CountDownLatch(size);
    IntStream.range(0,size).forEach(
        r-> executorService.execute( () -> {
          System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
          try {
            Thread.sleep(1000);//模拟耗时操作
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);
          countDownLatch.countDown();
        })

    );
    executorService.shutdown();
    countDownLatch.await();
    System.out.println("Finish countDownLatch Test");
  }

}

运行结果:
AQS原理应用(一):CountDownLatch的典型用法和实现原理_第1张图片
情况②:设定核心线程数与遍历次数和countdownLatch不等时,也是同样的效果。
注:执行完的线程也会进入阻塞状态

public class CountDownLatchTest {

  private static final int size = 8;

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = new ThreadPoolExecutor(5,10, 0,TimeUnit.SECONDS,
        new LinkedBlockingDeque<Runnable>());
    CountDownLatch countDownLatch = new CountDownLatch(size);
    IntStream.range(0,size).forEach(
        r-> executorService.execute( () -> {
          System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
          try {
            Thread.sleep(1000); //模拟耗时操作
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);
          countDownLatch.countDown();
        })

    );
    executorService.shutdown();
    countDownLatch.await();
    System.out.println("Finish countDownLatch Test");
  }

结果:
AQS原理应用(一):CountDownLatch的典型用法和实现原理_第2张图片

(二)实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。

做法是初始化一个共享的 CountDownLatch 对象,将其计数器初始化为 1 :new CountDownLatch(1),多个线程在开始执行任务前首先 coundownlatch.await(),当主线程调用 countDown() 时,计数器变为 0,多个线程同时被唤醒。

public class CountDownLatchTest1 {

  private static final int size = 8;

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = new ThreadPoolExecutor(5,10, 0,TimeUnit.SECONDS,
        new LinkedBlockingDeque<Runnable>());
    CountDownLatch countDownLatch = new CountDownLatch(1);
    IntStream.range(0,size).forEach(
        r-> executorService.execute( () -> {
          System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
          try {
            countDownLatch.await();
            Thread.sleep(1000);//模拟耗时操作
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);

        })

    );
    executorService.shutdown();
    countDownLatch.countDown();
    System.out.println("Finish countDownLatch Test");
  }

}

运行结果:
AQS原理应用(一):CountDownLatch的典型用法和实现原理_第3张图片

(三)死锁的检测:

一个非常方便的使用场景是,你可以使用 n 个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁。

public class CountDownLatchTest2 {
  public static void main(String[] args) throws InterruptedException {
    System.out.println("Hello World!");
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    byte[] i = new byte[0];
    byte[] j = new byte[0];
    final CountDownLatch countDownLatch = new CountDownLatch(2);
    executorService.execute(new DeadThread1(i, j,countDownLatch));
    executorService.execute(new DeadThread2(i, j,countDownLatch));
    countDownLatch.await();
    System.out.println("done !!!");
  }

  public static class DeadThread1 implements Runnable {

    private byte[] i;
    private byte[] j;
    private CountDownLatch countDownLatch;

    public DeadThread1(byte[] i, byte[] j, CountDownLatch countDownLatch) {
      this.i = i;
      this.j = j;
      this.countDownLatch = countDownLatch;
    }


    @Override
    public void run() {
      synchronized (i) {
        try {
          System.out.println(Thread.currentThread().getName() + "step1 is running!!");
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (j) {
          System.out.println(Thread.currentThread().getName() + " step2 is running!!");
          countDownLatch.countDown();
          System.out.println(Thread.currentThread().getName() + " step3 is end!!");
        }
      }
    }
  }

  public static class DeadThread2 implements Runnable {

    private byte[] i;
    private byte[] j;
    private CountDownLatch countDownLatch;

    public DeadThread2(byte[] i, byte[] j, CountDownLatch countDownLatch) {
      this.i = i;
      this.j = j;
      this.countDownLatch = countDownLatch;
    }


    @Override
    public void run() {
      synchronized (j) {
        try {
          System.out.println(Thread.currentThread().getName() + " step1 is running!!");
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (i) {
          System.out.println(Thread.currentThread().getName() + " step2 is running!!");
          countDownLatch.countDown();
          System.out.println(Thread.currentThread().getName() + " step3 is end!!");
        }
      }
    }
  }
}

分析:由于发生死锁,所以子线程并没有执行countdown()方法,所以主线程调用await()发生阻塞,没有打印出“done !!!”
运行结果:
AQS原理应用(一):CountDownLatch的典型用法和实现原理_第4张图片

三、CountDownLatch实现原理

源码:
CountDownLatch类内,与ReentrantLock类似,有静态内部类AbstractQueuedSynchronizer的Sync
,并重写了父类的方法

  • tryAcquireShared():共享方式,尝试获取资源方法,能获取到返回true
  • tryReleaseShared():共享方式,尝试释放资源方法,能获取到返回true
public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

(1)CountDownLatch()构造方法,初始化Sync
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
(2) countDown() -同步器释放一个资源,计算器减1
	/**
	* 同步器释放一个资源,计算器减1
	**/
    public void countDown() {
        sync.releaseShared(1);
    }
    
    public final boolean releaseShared(int arg) {
    //判断是否能释放资源
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}
     protected boolean tryReleaseShared(int releases) {
      // Decrement count; signal when transition to zero
      //自旋
      for (;;) {
      	  //获得当前计数器的数值
          int c = getState();
          if (c == 0)
          	  //如果计数器为0,直接返回
              return false;
          int nextc = c-1;
          //调用cas,设置修改state = c-1
          if (compareAndSetState(c, nextc))
              return nextc == 0;
      }
  }
(3)await()-判断当前计数器数值,如果为0,
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    public final void acquireSharedInterruptibly(int arg)
         throws InterruptedException {
     if (Thread.interrupted())
         throw new InterruptedException();
         //如果当前计数器state为0,await()执行完成
         //如果当前计数器state部位0,调用doAcquireSharedInterruptibly,当前线程进入阻塞状态
     if (tryAcquireShared(arg) < 0)
         doAcquireSharedInterruptibly(arg);
 }
  protected int tryAcquireShared(int acquires) {
       return (getState() == 0) ? 1 : -1;
   }

四、CountDownLatch的不足

CountDownLatch 是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当 CountDownLatch 使用完毕后,它不能再次被使用。

你可能感兴趣的:(java并发)