package thead.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolNewCached02ReuseExample {

    public static void main(String[] args) throws InterruptedException {
        // 创建一个缓存线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 提交多个任务
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " executed by: " + Thread.currentThread().getName());
                try {
                    // 模拟任务执行时间
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 等待 1 秒钟，确保线程池中的线程已经执行了一些任务
        Thread.sleep(1000);

        // 再次提交一些任务，观察线程是否复用
        for (int i = 5; i < 1000; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " executed by: " + Thread.currentThread().getName());
                try {
                    // 模拟任务执行时间
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 等待所有任务完成
        Thread.sleep(5000);
        executorService.shutdown();
    }
}
