在 Java 中,有几种内置的线程池实现,每种都有不同的使用场景和特点。以下是常见的几种线程池实现方式,以及它们的详细步骤流程和示例代码。
步骤流程:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolExample {
public static void main(String[] args) {
int numThreads = 5;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
executor.execute(() -> {
System.out.println("Task " + taskNumber + " executed by thread: " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
implementation 'org.apache.maven.plugins:maven-compiler-plugin:3.8.1'
步骤流程:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
executor.execute(() -> {
System.out.println("Task " + taskNumber + " executed by thread: " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
SingleThreadExecutor(单线程线程池):
步骤流程:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
executor.execute(() -> {
System.out.println("Task " + taskNumber + " executed by thread: " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
这些是 Java 中常见的线程池实现方式以及相应的步骤流程和示例代码。你可以根据你的应用场景选择适合的线程池来管理线程。