本文目录导读:

我来介绍几种Java单线程池的常见编写案例。
基础单线程池示例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SingleThreadPoolExample {
public static void main(String[] args) {
// 创建单线程池
ExecutorService executor = Executors.newSingleThreadExecutor();
// 提交任务
for (int i = 1; i <= 5; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("任务 " + taskId + " 开始执行,线程: " +
Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务 " + taskId + " 执行完成");
});
}
// 关闭线程池
executor.shutdown();
}
}
带返回结果的单线程池
import java.util.concurrent.*;
public class SingleThreadPoolWithResult {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
// 提交带返回值的任务
Future<String> future = executor.submit(() -> {
Thread.sleep(2000);
return "任务执行结果:" + System.currentTimeMillis();
});
System.out.println("等待任务执行...");
// 获取结果(会阻塞直到任务完成)
String result = future.get();
System.out.println("获取到结果:" + result);
executor.shutdown();
}
}
任务队列管理示例
import java.util.concurrent.*;
import java.util.*;
public class TaskQueueManagement {
public static void main(String[] args) throws InterruptedException {
// 自定义线程工厂
ThreadFactory threadFactory = new ThreadFactory() {
private int count = 0;
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("单线程池-任务-" + (++count));
thread.setDaemon(false);
return thread;
}
};
// 使用自定义线程工厂创建单线程池
ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
// 提交多个任务
for (int i = 1; i <= 3; i++) {
final int taskId = i;
executor.execute(() -> {
System.out.println("任务" + taskId + " 开始");
// 模拟耗时操作
for (int j = 0; j < 5; j++) {
System.out.println("任务" + taskId + " 执行中...步骤" + (j+1));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("任务" + taskId + " 完成");
});
}
// 优雅关闭
executor.shutdown();
// 等待所有任务完成
if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("所有任务执行完毕");
} else {
System.out.println("任务未在指定时间内完成");
}
}
}
实际应用:订单处理系统
import java.util.concurrent.*;
import java.util.*;
public class OrderProcessingSystem {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Queue<String> pendingOrders = new ConcurrentLinkedQueue<>();
// 添加订单
public void addOrder(String orderId) {
pendingOrders.offer(orderId);
executor.submit(() -> processOrder(orderId));
}
// 处理订单
private void processOrder(String orderId) {
System.out.println("开始处理订单: " + orderId +
" [线程: " + Thread.currentThread().getName() + "]");
try {
// 模拟订单处理步骤
Thread.sleep(1000);
System.out.println("订单 " + orderId + " - 步骤1: 验证完成");
Thread.sleep(1000);
System.out.println("订单 " + orderId + " - 步骤2: 支付处理");
Thread.sleep(1000);
System.out.println("订单 " + orderId + " - 步骤3: 库存更新");
System.out.println("订单 " + orderId + " 处理完成!");
} catch (InterruptedException e) {
System.err.println("订单 " + orderId + " 处理被中断");
}
}
// 获取待处理订单数量
public int getPendingOrderCount() {
return pendingOrders.size();
}
// 关闭系统
public void shutdown() {
executor.shutdown();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
}
public static void main(String[] args) {
OrderProcessingSystem system = new OrderProcessingSystem();
// 模拟添加多个订单
for (int i = 1; i <= 3; i++) {
String orderId = "ORD-" + System.currentTimeMillis();
system.addOrder(orderId);
System.out.println("已添加订单: " + orderId);
}
// 等待一段时间后关闭系统
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
system.shutdown();
}
}
异常处理示例
import java.util.concurrent.*;
public class ExceptionHandlingExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
// 方法1: 使用try-catch在任务内部处理异常
executor.submit(() -> {
try {
System.out.println("任务1开始");
int result = 10 / 0; // 模拟异常
} catch (Exception e) {
System.err.println("任务1出现异常: " + e.getMessage());
}
});
// 方法2: 使用Future捕获异常
Future<Integer> future = executor.submit(() -> {
System.out.println("任务2开始");
return 10 / 0; // 模拟异常
});
try {
Integer result = future.get();
System.out.println("任务2结果: " + result);
} catch (ExecutionException e) {
System.err.println("捕获到任务2的异常: " + e.getCause().getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
// 方法3: 使用UncaughtExceptionHandler
ThreadFactory threadFactory = r -> {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler((thread, e) ->
System.err.println("未捕获异常: " + e.getMessage()));
return t;
};
ExecutorService executor2 = Executors.newSingleThreadExecutor(threadFactory);
executor2.submit(() -> {
System.out.println("任务3开始");
throw new RuntimeException("任务3的运行时异常");
});
executor.shutdown();
executor2.shutdown();
}
}
- 任务顺序执行:所有任务按提交顺序依次执行
- 线程复用:只创建一个线程,所有任务共享
- 任务队列:使用无界LinkedBlockingQueue存储等待任务
- 优雅关闭:支持shutdown()和shutdownNow()方法
使用建议:
- 适合需要保证任务执行顺序的场景
- 避免在单线程池中执行长时间阻塞操作
- 注意异常处理,防止线程异常终止
- 合理设置超时时间,避免线程池无法关闭
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播