1、减法计数器
public static void main(String []args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 1;i<=6;i++){ new Thread(()->{ System.out.println(Thread.currentThread().getName()+" go out"); countDownLatch.countDown(); }).start(); } countDownLatch.await(); System.out.println("close door"); }
2、加法计数器
public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> { System.out.println("Run");//先运行参数,达到目标值后运行lambda表达式中的代码 }); for (int i = 1; i <= 7; i++) { final int temp = i; new Thread(() -> { //lambda表达式中不能直接取i,需要通过定义final私有的中间变量 System.out.println(Thread.currentThread().getName() + temp); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } }
3、线程限流
public static void main(String[] args) { //线程数量:限流 Semaphore semaphore = new Semaphore(3); for (int i = 1;i<=6;i++){ new Thread(()->{ try { semaphore.acquire();//得到 System.out.println(Thread.currentThread().getName()+"已入库"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+"已出库"); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release();//释放 } },String.valueOf(i)).start(); } }