Java多线程面试题:如何创建线程池?

Java Q&A Hub 使用 GPT-4o-mini 回答

问题:

Java面试题之多线程 如何创建一个Java线程池?

回答:

在Java中,创建一个线程池通常使用java.util.concurrent包中的ExecutorService接口及其实现类。最常用的实现类是ThreadPoolExecutor,但通常我们会使用Executors工厂类来简化线程池的创建。

以下是创建线程池的几种常见方式:

1. 使用 Executors 工厂类

固定大小线程池

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

public class FixedThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
            });
        }

        executorService.shutdown(); // 关闭线程池
    }
}

缓存线程池

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

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

        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
            });
        }

        executorService.shutdown(); // 关闭线程池
    }
}

单线程池

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

public class SingleThreadExecutorExample {
    public static void main(String[] args) {
        // 创建一个单线程的线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
            });
        }

        executorService.shutdown(); // 关闭线程池
    }
}

2. 使用 ThreadPoolExecutor 直接创建线程池

如果需要更细粒度的控制,可以直接使用ThreadPoolExecutor构造函数:

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个自定义的线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, // corePoolSize
                4, // maximumPoolSize
                60, // keepAliveTime
                TimeUnit.SECONDS, // time unit for keepAliveTime
                new LinkedBlockingQueue<>() // work queue
        );

        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
            });
        }

        executor.shutdown(); // 关闭线程池
    }
}

总结

  • 使用Executors类可以快速创建常用类型的线程池。
  • 使用ThreadPoolExecutor可以自定义线程池的参数,如核心线程数、最大线程数、线程存活时间等。
  • 记得在使用完线程池后调用shutdown()方法来关闭线程池,释放资源。