面试官:手写线程池,我:?面试官:回去等通知吧!

327 阅读14分钟

本文主要是整理一些多线程面试常见的手撕题,可能不是很全,后续会继续补充,感兴趣的同学可以看一下!

本文详细代码全都放在 Github 了,有需要的同学可以上 Github 自取:

github.com/DIDA-lJ/Juc…

1. 写两个线程轮流打印 1 - 100

这个是一道简单的 Java 多线程程序题,一个线程打印奇数,另外一个线程打印偶数,线程之间通过 wait()和 notifyAll()方法进行协调,确保轮流打印数字

/**
 * @author linqi
 * @version 1.0.0
 * @description 两个线程轮流打印 1~100
 */

public class AlternatePrinting {
    private int currentNumber = 1;
    private final Object lock = new Object();

    public static void main(String[] args) {
        AlternatePrinting ap = new AlternatePrinting();

        // 创建奇数打印线程
        Thread oddPrinter = new Thread(() -> {
            ap.printNumber(true);
        });
        oddPrinter.start();

        // 创建偶数打印线程
        Thread evenPrinter = new Thread(() -> {
            ap.printNumber(false);
        });
        evenPrinter.start();
    }

    /**
     * 根据 isOdd 标志打印奇数或者偶数
     *
     * @param flag true:奇数 false:偶数
     */
    private void printNumber(boolean flag) {
        while (currentNumber <= 100) {
            synchronized (lock) {
                while ((flag && currentNumber % 2 == 0) || (!flag && currentNumber % 2 == 1)) {
                    try {
                        // 如果当前线程不应该打印,等待
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (currentNumber <= 100) {
                    System.out.println("Thread " + (flag ? "Odd " : "Even") + ": " + currentNumber);
                    currentNumber++;
                    lock.notifyAll();
                }
            }
        }
    }


}

2. 三个线程交替顺序打印出 1-100

针对每个线程分配一个打印范围,第一个线程打印 3 的倍数,第二个线程打印 3n + 1 的数,第三个线程打印 3n + 2 的数(其中n是非负整数),同时使用一种机制来确保三个线程交替执行。

public class AlternatePrintingThreeThreads {
    /**
     * 当前要打印的数字
     */
    private int currentNumber = 1;
    /**
     * 用于同步的锁对象
     */
    private final Object lock = new Object();
    /**
     * 控制哪个线程应该打印的标识 0:3n ,1:3n + 1,2: 3n + 2
     */
    private int turn = 0;

    public static void main(String[] args) {
        AlternatePrintingThreeThreads ap = new AlternatePrintingThreeThreads();

        // 创建并启动三个线程
        Thread t1 = new Thread(() -> ap.printNumbers(0));
        Thread t2 = new Thread(() -> ap.printNumbers(1));
        Thread t3 = new Thread(() -> ap.printNumbers(2));

        t1.start();
        t2.start();
        t3.start();

    }

    /**
     * 根据 turn 的值打印对应范围的数字
     *
     * @param offset 0:3n 1:3n+1 2:3n+2
     */
    private void printNumbers(int offset) {
        while (currentNumber <= 100) {
            synchronized (lock) {
                while ((turn % 3) != offset) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (currentNumber <= 100 && (currentNumber - 1) % 3 == offset) {
                    System.out.println("Thread " + (offset + 1) + " printed: " + currentNumber);
                    currentNumber++;
                    turn = (turn + 1) % 3;
                    lock.notifyAll();
                }
            }
        }
    }
}

在程序中,使用 ture 变量来控制线程的打印,然后每个线程打印前检查一下 turn 的值,如果不是轮到自己打印,就调用了 wait 方法进入等待状态。当一个线程打印完毕之后,更新 turn 的值,并且通过 notifyAll()方法唤醒其他可能在等待的线程。

3. 多线程问题:线程 A,B,C 分别打印 1、2、3,顺序执行 10 次

为了顺序执行10次打印任务,其中线程A打印1,线程B打印2,线程C打印3,我们可以使用一个共享的计数器来跟踪当前的打印轮次,并确保每个线程在正确的轮次中执行。

/**
 * @author linqi
 * @version 1.0.0
 * @description 线程 A、B、C 分别打印 1,2,3 顺序执行 10 次
 */

public class SequentialPrinting {
    /**
     * 当前线程打印的次数
     */
    private int count = 0;
    /**
     * 用于同步锁对象
     */
    private final Object lock = new Object();

    public static void main(String[] args) {
        SequentialPrinting printer = new SequentialPrinting();

        // 创建并启动线程
        Thread tA = new Thread(() -> printer.printNumber(1), "A");
        Thread tB = new Thread(() -> printer.printNumber(2), "B");
        Thread tC = new Thread(() -> printer.printNumber(3), "C");

        tA.start();
        tB.start();
        tC.start();
    }

    private void printNumber(int numberToPrint) {
        for (int i = 0; i < 10; i++) {
            synchronized (lock) {
                while (count % 3 != numberToPrint - 1) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (count < 30) {
                    System.out.println("Thread " + Thread.currentThread().getName() + ": " + numberToPrint);
                    count++;
                    lock.notifyAll();
                }
            }
        }
    }
}

在这个程序中,count变量用来跟踪当前的打印轮次,并且确保每个线程在正确的轮次执行。每个线程都会检查count的值,如果当前轮次不是自己的,就会调用wait()方法进入等待状态。当一个线程打印完毕后,它会增加count的值,并通过notifyAll()方法唤醒其他可能在等待的线程。

注意,count变量的上限设置为30(10轮,每轮3个数字),以确保程序只执行10轮打印。每个线程都会检查这个条件,以避免超出所需的打印轮次。

此程序会按顺序(线程A、线程B、线程C)执行打印任务,每个线程打印自己的数字,总共进行10轮。

4. 计数累加怎么线程安全,可以怎么实现,100个线程,每个线程累加100次

以下是一个简单的Java示例,演示了如何使用AtomicInteger来实现线程安全的计数累加。在这个示例中,我们将创建100个线程,并且每个线程将对计数器执行100次累加操作。

public class AtomicCounterDemo {

    private static final AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        // 创建100个线程来增加计数器的值
        ExecutorService executor = Executors.newFixedThreadPool(100);

        // 提交 100 个任务,每个任务执行 100 次累加
        for (int i = 0; i < 100; i++) {
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        counter.incrementAndGet();
                    }
                }
            });
        }

        // 关闭线程池
        executor.shutdown();
        // 等待所有任务完成
        executor.awaitTermination(1, TimeUnit.HOURS);

        // 输出最终的值
        System.out.println("Final counter value: " + counter.get());
    }
}

在这个示例中,我们定义了一个 AtomicInteger 类型的静态变量counter作为我们的计数器。incrementCounterHundredTimes方法包含了一个循环,它会使计数器递增100次。由于AtomicInteger的incrementAndGet方法是线程安全的,所以我们不需要额外的同步措施。

在main方法中,我们创建了一个拥有100个线程的线程池,并提交了100个任务,每个任务都会执行incrementCounterHundredTimes方法。在所有任务完成后,我们输出最终的计数值。由于每个线程都会将计数器增加100,所以最终的计数值应该是 100 * 100 = 10000。

5. 线程交叉打印12A34B56C,多种实现方式(一个打印数字,一个打印字母)

示例 1:使用wait()和notifyAll()

/**
 * @author linqi
 * @version 1.0.0
 * @description 线程交替打印 12A34B56C 使用 wait() 和 notifyAll()
 */

public class CrossPrint {
    private static final Object lock = new Object();
    private static boolean printNumber  = true;

    public static void main(String[] args) {
        Thread printNumberThread = new Thread(() ->{
            for(int i = 1; i <= 52; i=i+2){
                synchronized (lock){
                    while(!printNumber){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(i);
                    System.out.print(i + 1);
                    printNumber = false;// 打印切换标志
                    lock.notifyAll();// 唤醒等待的线程
                }
            }
        });

        Thread printLetterThread = new Thread(() ->{
            for(char c = 'A'; c <= 'Z'; c++){
                synchronized (lock){
                    while(printNumber){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(c);
                    printNumber = true;// 打印切换标志
                    lock.notifyAll();// 唤醒等待的线程
                }
            }
        });

        printLetterThread.start();
        printNumberThread.start();
    }
}

示例 2:使用ReentrantLock和Condition

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class CrossPrintWithLock {
    private  static final Lock lock = new ReentrantLock();
    private static final Condition printNumberCondition = lock.newCondition();
    private static final Condition printLetterCondition = lock.newCondition();
    private static boolean printNumber = true;

    public static void main(String[] args) {
        Thread printNumberThread = new Thread(() ->{
            for(int i = 1; i <= 52; i=i+2){
                synchronized (lock){
                    while(!printNumber){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(i);
                    System.out.print(i + 1);
                    printNumber = false;// 打印切换标志
                    lock.notifyAll();// 唤醒等待的线程
                }
            }
        });

        Thread printLetterThread = new Thread(() ->{
            for(char c = 'A'; c <= 'Z'; c++){
                synchronized (lock){
                    while(printNumber){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(c);
                    printNumber = true;// 打印切换标志
                    lock.notifyAll();// 唤醒等待的线程
                }
            }
        });

        printLetterThread.start();
        printNumberThread.start();
    }

}

6. 两个线程交替打印ABCD..Z字母,一个大写一个小写

目标输出:AbCdEfGhIjKlMnOpQrStUvWxYz

代码示例:

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class AlternateLetterPrinting {
    private static final Object lock = new Object();
    private static char currentLetter = 'A';
    private static boolean printUpperCase = true;

    public static void main(String[] args) {
        Thread upperCasePrinter = new Thread(()-> printLetter(true));
        Thread lowerCasePrinter = new Thread(()-> printLetter(false));

        upperCasePrinter.start();
        lowerCasePrinter.start();
    }

    private static void printLetter(boolean isUpperCaseThread) {
        while (currentLetter <= 'Z'){
            synchronized (lock){
                while (printUpperCase != isUpperCaseThread) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (currentLetter > 'Z') {
                    break;
                }
                if (isUpperCaseThread) {
                    System.out.print( currentLetter);
                } else {
                    System.out.print(Character.toLowerCase( currentLetter));
                }

                printUpperCase = !printUpperCase;
                currentLetter++;

                lock.notifyAll();
            }
        }
    }
}

7. 两个线程交替打印出a1b2c3.....z26

示例代码:

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class AlternatePrintingNumberLetter {
    private static final Object lock = new Object();
    /**
     *  用于计数,确认打印的字母和数字
     */
    private static int count = 1;
    /**
     * 控制标记,用于控制是否打印数字
     */
    private static boolean printNumber = false;

    public static void main(String[] args) {
        // 创建打印数字的线程
        Thread printNumberThread = new Thread(() ->{
            while(count <= 26){
                synchronized (lock){
                    while(!printNumber){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if(count <= 26){
                        System.out.print(count);
                        count++;
                        printNumber = false;
                        lock.notifyAll();
                    }
                }
            }
        });
        // 创建打印字母的线程
        Thread printLetterThread = new Thread(()->{
            while(count <= 26){
                synchronized (lock){
                    while(printNumber) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (count <= 26){
                        char letter = (char)('a' + count - 1);
                        System.out.print(letter);
                        printNumber = true;
                        lock.notify();
                    }
                }
            }
        });
        printNumberThread.start();
        printLetterThread.start();
    }

}

这个demo中,我们使用了Object类的wait()和notifyAll()方法来控制两个线程的交替执行。wait()方法会使当前线程等待,直到其他线程调用notifyAll()方法唤醒所有在该对象上等待的线程。

我们使用count变量来跟踪打印的进度,printNumber标志来控制哪个线程应该打印。当一个线程打印完毕后,它会更改printNumber标志,并通过notifyAll()唤醒其他线程。这样,两个线程就可以交替执行,直到打印完z26。

8. 两个线程,一个打印abcd,一个打印1234,需求交替打印出a1b2c3d4a1b2c3d4 ; 打印10轮

我们需要一个共享资源来控制线程之间的交替执行,并确保它们按顺序打印。以下是一个简单的Java示例,其中包含必要的同步机制以实现所需的交替打印:

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class AlternatePrintDemo {

    private static final Object lock = new Object();
    /**
     * 0 表示打印字母,1 表示数字
     */
    private static int state = 0;
    private static int round = 0;

    public static void main(String[] args) {
        Thread printLetters = new Thread(() ->{
            for(int i = 0; i < 40;i++){
                synchronized (lock){
                    while(state != 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if(round < 10){
                        char letter = (char)('a' + (i % 4));
                        System.out.print(letter);
                        state = 1;
                        lock.notifyAll();
                    }
                }
            }
        });

        Thread printNumbers = new Thread(() ->{
            for(int i = 0; i < 40 ;i++){
                synchronized (lock){
                    while(state != 1){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if(round < 10){
                        int number = (i % 4 )+ 1;
                        System.out.print(number);

                        if( (i + 1) % 4 == 0){
                            round++;
                        }

                        state = 0;
                        lock.notifyAll();
                    }
                }
            }
        });

        printNumbers.start();
        printLetters.start();
    }

}

在这个示例中,我们使用了一个state变量来控制哪个线程应该打印。state为0时,字母线程打印;state为1时,数字线程打印。我们还使用了一个round变量来跟踪已经完成的打印轮数。当达到10轮时,两个线程将停止打印。

注意,这个示例依赖于Java对象的内置锁(通过synchronized关键字实现)和等待/通知机制(通过wait()和notifyAll()方法实现)。这种方法确保了线程之间的正确同步,以实现交替打印。

9. 假设有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?

方式一:只使用 join

import java.util.Random;

/**
 * @author linqi
 * @version 1.0.0
 * @description T2 在 T1 之后执行,T3 在 T2 之后执行
 */

public class ThreadJoinDemo {

    public static void main(String[] args) {
        Thread t1 = new Thread(new Task("T1"), "T1");
        Thread t2 = new Thread(new Task("T2"), "T2");
        Thread t3 = new Thread(new Task("T3"), "T3");


        // 启动 t1
        t1.start();
        try {
            t1.join();
            t2.start();
            t2.join();
            t3.start();
            t3.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    private static class Task implements Runnable {
        private String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            System.out.println(name + " 开始执行!");
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(name + " 执行完毕!");
            long endTime = System.currentTimeMillis();
            System.out.println(name + " 执行时间:" + (endTime - startTime) + "ms");
            System.out.println("--------------------------------");
        }
    }
}

在这个示例中,Task是一个实现了Runnable接口的类,它代表了一个可以被线程执行的任务。在main方法中,我们创建了三个线程t1、t2和t3,分别对应T1、T2和T3。我们首先启动t1,然后使用t1.join()等待它完成。一旦t1完成,我们启动t2并等待它完成,依此类推。这种方法确保了线程按照T1 -> T2 -> T3的顺序执行。

方式二:使用join配合CountDownLatch的一个简单示例:

import java.util.concurrent.CountDownLatch;

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class ThreadExecutionOrderDemo {
    private static CountDownLatch t1ToT2Latch = new CountDownLatch(1);
    private static CountDownLatch t2ToT3Latch = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            long startTime = System.currentTimeMillis();
            System.out.println("T1 开始执行!");
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("T1 执行时间:" + (endTime - startTime) + "ms");
            System.out.println("T1 执行完毕!");
            System.out.println("------------------------------------------------");
            t1ToT2Latch.countDown();
        }, "T1");

        Thread t2 = new Thread(() -> {
            try{
                t1ToT2Latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long startTime = System.currentTimeMillis();
            System.out.println("T2 开始执行!");
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("T2 执行时间:" + (endTime - startTime) + "ms");
            System.out.println("T2 执行完毕!");
            System.out.println("------------------------------------------------");
            t2ToT3Latch.countDown();
        }, "T2");
        Thread t3 = new Thread(() -> {
            try{
                t2ToT3Latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long startTime = System.currentTimeMillis();
            System.out.println("T3 开始执行!");
            try {
                Thread.sleep((long) (Math.random() * 1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("T3 执行时间:" + (endTime - startTime) + "ms");
            System.out.println("T3 执行完毕!");
        }, "T3");

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();


    }

}

在这个示例中,t1ToT2Latch和t2ToT3Latch是两个CountDownLatch实例,分别用于控制T1到T2和T2到T3的执行顺序。T2线程在开始执行其主要任务之前会等待t1ToT2Latch计数到0,而T3线程则会等待t2ToT3Latch计数到0。这样,我们就可以确保T2在T1完成后执行,T3在T2完成后执行。

10. 仿购票系统,目前有1000张票,同时有10个购票窗口,模拟购票流程,打印购票结果,比如:从1窗口购买1张票,剩余999张票

以下是一个简单的Java示例,模仿了一个购票系统。这个系统有1000张票,并且有10个购票窗口。每个窗口可以购买票,每次购票后,系统会更新剩余票数并打印出来。

import java.util.Random;

/**
 * @author linqi
 * @version 1.0.0
 * @description 购票系统
 */

public class TicketSystemDemo {
    /**
     * 总共票数
     */
    private static final int TOTAL_TICKETS = 1000;
    /**
     * 剩余票数
     */
    private static int remainingTICKETS = TOTAL_TICKETS;
    /**
     * 锁对象,用于同步
     */
    private static final Object lock = new Object();

    public static void main(String[] args) {
        // 创建线程,并且启动
        for (int i = 0; i < 10; i++) {
            new Thread(new TicketSeller(i)).start();
        }

    }

    private static class TicketSeller implements Runnable {
        private int windowNumber;

        public TicketSeller(int windowNumber) {
            this.windowNumber = windowNumber;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (remainingTICKETS > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        buyTicket();
                    } else {
                        break;
                    }
                    // 模拟购票后的其他操作,增加随机性
                    try {
                        Thread.sleep((long) (Math.random() * 1000));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }


        private void buyTicket() {
            int number = new Random().nextInt(10);
            if(remainingTICKETS   >= number && number > 0){
                remainingTICKETS = remainingTICKETS - number;
                System.out.println("从窗口 G1000" + windowNumber + " 购买了 " + number + " 张票, 还剩 " + remainingTICKETS + " 张票");
            }
        }
    }
}

在这个示例中,TicketSystemDemo 类包含了一个模拟购票系统的主程序。TicketWindow 类实现了 Runnable接口,代表一个购票窗口。每个窗口在一个单独的线程中运行,尝试购买票,直到票卖完为止。

关键点是使用 synchronized 块来同步对剩余票数的访问,以避免多个线程同时修改票数导致数据不一致。当剩余票数为0时,窗口线程将结束执行。

11. 有一批任务Tasks, 现在我需要实现按批次执行,并且批次可以动态指定,例如[1,3,5,7]第一批执行,[11,13,15,17]第二批执行,..., 最后没有指定的任务就最后一起执行掉。批次之间需要按顺序,前一批执行完了才执行下一批

import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class TaskRunner {

    public static void main(String[] args) {
        // 假设创建了 100 个任务
        List<Runnable> tasks = TaskRunner.createTasks();

        // 第一批和第二批执行的任务索引
        List<Integer> batch1 = new ArrayList<Integer>(Arrays.asList(1, 3, 5, 7));
        List<Integer> batch2 = new ArrayList<Integer>(Arrays.asList(11, 13, 15, 17));

        List<List<Integer>> batchs = new ArrayList<>();
        batchs.add(batch1);
        batchs.add(batch2);

        try {
            runTasksInBatches(tasks, batchs);
            System.out.println("====== 全部任务执行完成!======");

        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void runTasksInBatches(List<Runnable> tasks, List<List<Integer>> batchs) throws ExecutionException, InterruptedException {
        // 使用固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 执行第一批任务
        List<Future<Void>> futures = new ArrayList<Future<Void>>();
        Set<Integer> allBatchTaskIndexs = new HashSet<Integer>();
        for (int i = 0; i < batchs.size(); i++) {
            System.out.println("====== 第 " + (i + 1) + " 批任务开始执行!======");
            for (int index : batchs.get(i)) {
                Future<Void> future = (Future<Void>) executor.submit(tasks.get(index));
                futures.add(future);
                allBatchTaskIndexs.add(index);
            }
            // 等待一批任务完成
            for (Future<Void> f : futures) {
                f.get();
            }
            futures.clear();
            System.out.println("====== 第 " + (i + 1) + " 批任务执行完成!======");
        }

        // 执行剩下的任务
        System.out.println("====== 最后 1 批任务开始执行!======");
        for (int i = 0; i < tasks.size(); i++) {
            if (!allBatchTaskIndexs.contains(i)) {
                executor.submit(tasks.get(i));
            }
        }


        // 关闭线程池,并且等待所有任务执行
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有任务执行完毕
        }
        System.out.println("====== 最后 1 批任务执行完成!======");
    }

    private static List<Runnable> createTasks() {
        List<Runnable> tasks = new ArrayList<>();
        // 创建任务的逻辑
        for (int i = 0; i < 30; i++) {
            final int taskId = i;
            tasks.add(() -> {
                try {
                    long startTime = System.currentTimeMillis();
                    Thread.sleep((long) (Math.random() * 1000));
                    long endTime = System.currentTimeMillis();
                    System.out.println("执行任务,任务 ID :" + taskId + ",耗时:" + (endTime - startTime) + "ms");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        return tasks;
    }
}

12. 手写线程池

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author linqi
 * @version 1.0.0
 * @description
 */

public class ThreadPoolTrader implements Executor {

    private final AtomicInteger ctl = new AtomicInteger(0);

    private volatile int corePoolSize;
    private volatile int maximumPoolSize;

    private final BlockingQueue<Runnable> workQueue;

    public ThreadPoolTrader(int corePoolSize, int maximumPoolSize, BlockingQueue<Runnable> workQueue) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
    }

    @Override
    public void execute(Runnable command) {
        int c = ctl.get();
        if (c < corePoolSize) {
            if (!addWorker(command)) {
                reject();
            }
            return;
        }
        if (!workQueue.offer(command)) {
            if (!addWorker(command)) {
                reject();
            }
        }
    }

    private boolean addWorker(Runnable firstTask) {
        if (ctl.get() >= maximumPoolSize) {
            return false;
        }

        Worker worker = new Worker(firstTask);
        worker.thread.start();
        ctl.incrementAndGet();
        return true;
    }

    private final class Worker implements Runnable {

        final Thread thread;
        Runnable firstTask;

        public Worker(Runnable firstTask) {
            this.thread = new Thread(this);
            this.firstTask = firstTask;
        }

        @Override
        public void run() {
            Runnable task = firstTask;
            try {
                while (task != null || (task = getTask()) != null) {
                    task.run();
                    if (ctl.get() > maximumPoolSize) {
                        break;
                    }
                    task = null;
                }
            } finally {
                ctl.decrementAndGet();
            }
        }

        private Runnable getTask() {
            for (; ; ) {
                try {
                    System.out.println("workQueue.size:" + workQueue.size());
                    return workQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void reject() {
        throw new RuntimeException("Error!ctl.count:" + ctl.get() + " workQueue.size:" + workQueue.size());
    }

    public static void main(String[] args) {
        ThreadPoolTrader threadPoolTrader = new ThreadPoolTrader(2, 2, new ArrayBlockingQueue<Runnable>(10));

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPoolTrader.execute(() -> {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                    System.out.println("任务编号:" + finalI);
            });
        }
    }

}