newFixedThreadPool
是 Java 中 java.util.concurrent.Executors
类的一个静态方法,用于创建一个固定大小的线程池。以下是关于这个方法的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案的详细解释。
newFixedThreadPool
方法创建一个线程池,该线程池的核心线程数和最大线程数都等于指定的参数(即线程池的大小)。当有新任务提交到线程池时,如果当前线程数小于核心线程数,即使有空闲线程,也会创建新线程来处理任务。如果当前线程数已经达到核心线程数,则新任务会被放入队列等待执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小为5的线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
原因:当线程池中的所有线程都在忙碌,且任务队列已满时,新提交的任务会被拒绝。
解决方案:
ThreadPoolExecutor
的自定义配置,设置合适的拒绝策略(如 CallerRunsPolicy
)。import java.util.concurrent.*;
public class CustomThreadPool {
public static void main(String[] args) {
int corePoolSize = 5;
int maxPoolSize = 10;
long keepAliveTime = 5000;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(10);
RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MILLISECONDS,
workQueue,
handler
);
// 提交任务...
}
}
原因:线程在执行完任务后未能正确释放资源,导致线程长时间占用内存。
解决方案:
try-finally
块确保资源释放。class WorkerThread implements Runnable {
@Override
public void run() {
try {
// 执行任务...
} finally {
// 释放资源...
}
}
}
通过以上解释和示例代码,希望能帮助你更好地理解和使用 newFixedThreadPool
方法。
领取专属 10元无门槛券
手把手带您无忧上云