这是一道常见的面试题,我使用了三种方法来实现

方法一 两线程交替打印

private static int count = 100;

private static boolean flag = true;
new Thread(() -> {
    while (count <= 200){
        if (flag == true){
            System.out.println(Thread.currentThread().getName() + "   " + count++);
            flag = false;   
        }
    }
}).start();

new Thread(() -> {
    while (count <= 200){
        if (flag == false){
            System.out.println(Thread.currentThread().getName() + "   " + count++);
            flag = true;
        }
    }
}).start();

方法二 CountDownLatch

注意 while(true) 循环

CountDownLatch countDownLatch = new CountDownLatch(100);

for (int i = 100; i < 200; i++) {
    int finalI = i;
    new Thread(() -> {
        //为什么要加 while(true) 循环:
        //线程启动后不一定立即执行,也就是会导致线程乱序执行
        //乱序的线程执行完一次if判断后就不再执行了
        System.out.println(Thread.currentThread().getName() + " NOW RUNNING");

        while (true){
            if (finalI == 200 - countDownLatch.getCount()){
                System.out.println(Thread.currentThread().getName() + "   " + finalI);
                countDownLatch.countDown();
                break;
            }
        }

    }).start();
}

方法三 Semaphore 信号量

Semaphore semaphore = new Semaphore(1);

for (int i = 100; i < 200; i++) {
    new Thread(() -> {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "   " + count);
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

    }).start();
}