面试必问! JUC 常用 4 大并发工具类是哪几个?( 二 )

<= 3; i++) {new Thread(new InitThread()).start();}// 主线程进入等待try {countDownLatch.await();System.out.println("Main do ites work.....");} catch (InterruptedException e) {e.printStackTrace();}}}
返回结果:
thread_13 ready init work .....thread_13.....continue do its workthread_13.....continue do its workthread_14 ready init work .....thread_14.....continue do its workthread_14.....continue do its workthread_15 ready init work .....thread_15.....continue do its workthread_11 ready init work step 1st.....begin stop 2nd.....thread_16 ready init work .....thread_16.....continue do its workthread_16.....continue do its workthread_15.....continue do its workthread_11 ready init work step 2nd.....Main do ites work.....BusiThread 12 do business-----BusiThread 12 do business-----BusiThread 12 do business-----
通过返回结果就可以很直接的看到业务线程是在初始化线程完全跑完之后,才开始执行的 。
基于微服务的思想,构建在 B2C 电商场景下的项目实战 。核心技术栈,是Boot + Dubbo。未来,会重构成Cloud。
项目地址:
「:」
,俗称栅栏锁,作用是让一组线程到达某个屏障,被阻塞,一直到组内的最后一个线程到达,然后屏障开放,接着,所有的线程继续运行 。
这个感觉和有点相似,但是其实是不一样的,所谓的差别,将在下面详解 。
的构造参数有两个 。
/*** Creates a new {@code CyclicBarrier} that will trip when the* given number of parties (threads) are waiting upon it, and* does not perform a predefined action when the barrier is tripped.** @param parties the number of threads that must invoke {@link #await}*before the barrier is tripped* @throws IllegalArgumentException if {@code parties} is less than 1*/public CyclicBarrier(int parties) {this(parties, null);}/*** Creates a new {@code CyclicBarrier} that will trip when the* given number of parties (threads) are waiting upon it, and which* will execute the given barrier action when the barrier is tripped,* performed by the last thread entering the barrier.** @param parties the number of threads that must invoke {@link #await}*before the barrier is tripped* @param barrierAction the command to execute when the barrier is*tripped, or {@code null} if there is no action* @throws IllegalArgumentException if {@code parties} is less than 1*/public CyclicBarrier(int parties, Runnable barrierAction) {if (parties <= 0) throw new IllegalArgumentException();this.parties = parties;this.count = parties;this.barrierCommand = barrierAction;}
很明显能感觉出来,上面的构造参数调用了下面的构造参数,是一个构造方法重载 。
首先这个第一个参数也树 Int 类型的,传入的是执行线程的个数,这个数量和不一样,这个数量是需要和线程数量吻合的, 则不一样, 可以大于等于,而只能等于,然后是第二个参数,第二个参数是 ,这个参数是当屏障开放后,执行的任务线程,如果当屏障开放后需要执行什么任务,可以写在这个线程中 。
主线程创建 (3,),然后由线程开始执行,线程A,B 执行完成后都调用了 await,然后他们都在一个屏障前阻塞者,需要等待线程 C 也,执行完成,调用 await 之后,然后三个线程都达到屏障后,屏障开放,然后线程继续执行,并且在屏障开放的一瞬间也开始执行 。
上代码:
package org.dance.day2.util;import org.dance.tools.SleepTools;import java.util.Map;import java.util.Random;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CyclicBarrier;/*** CyclicBarrier的使用** @author ZYGisComputer*/public class UseCyclicBarrier {/*** 存放子线程工作结果的安全容器*/private static ConcurrentHashMap resultMap = new ConcurrentHashMap