1.0 countdownlatch关键字的使用
package com.example.demo; import java.util.concurrent.CountDownLatch; /** * @ClassName ZeroEvenOdd * @Description: 1116. 打印零与奇偶数(多线程) * @Author xtanb * @Date 2019/9/23 * @Version V1.0 **/ public class ZeroEvenOdd { private int n; private CountDownLatch countDownLatchA; private CountDownLatch countDownLatchB; private CountDownLatch countDownLatchC; public ZeroEvenOdd(int n) { this.n = n; this.countDownLatchA = new CountDownLatch(0); this.countDownLatchB = new CountDownLatch(1); this.countDownLatchC = new CountDownLatch(1); } // printNumber.accept(x) outputs "x", where x is an integer. public void zero(IntConsumer printNumber) throws InterruptedException { for(int i=0;i<n;i++){ countDownLatchA.await(); printNumber.accept(0); countDownLatchA = new CountDownLatch(1); if(i%2==0){ countDownLatchB.countDown(); }else{ countDownLatchC.countDown(); } } } public void even(IntConsumer printNumber) throws InterruptedException { for(int i=1;i<=n;i=i+2){ countDownLatchB.await(); printNumber.accept(i); countDownLatchB = new CountDownLatch(1); countDownLatchA.countDown(); } } public void odd(IntConsumer printNumber) throws InterruptedException { for(int i=2;i<=n;i=i+2){ countDownLatchC.await(); printNumber.accept(i); countDownLatchC = new CountDownLatch(1); countDownLatchA.countDown(); } } public static void main(String[] args) { ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(10); IntConsumer printNumber = new IntConsumer(); new Thread(){ @Override public void run() { try { zeroEvenOdd.zero(printNumber); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); new Thread(){ @Override public void run() { try { zeroEvenOdd.odd(printNumber); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); new Thread(){ @Override public void run() { try { zeroEvenOdd.even(printNumber); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }