Executor框架详解
Executor框架应用
使用Executor框架解决仓库配货时的并发问题
基本思路:
- 因为仓库出库单出库配货时,存在资源共享问题(商品共享),所以多线程并发配货时存在同步问题
- 解决思路一:加锁
- 解决思路二:将配货动作封装成任务,交由单线程处理,即请求配货的过程是允许并发的,但真正的配货动作是有顺序的,依据队列的顺序一个一个的进行
package com.ahut.threadPool;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @author cheng
* @className: ThreadPoolTest
* @description:
* @dateTime
public class ThreadPoolTest implements Callable<Boolean> {
/**
* @description: 主函数
* @author cheng
* @dateTime
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个线程的线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 任务集合
List<Callable<Boolean>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Callable<Boolean> callable = new ThreadPoolTest("Thread-" + i, i);
list.add(callable);
}
// 结果集合
List<Future<Boolean>> futureList = new ArrayList<>();
for (Callable<Boolean> callable : list) {
Future<Boolean> future = executorService.submit(callable);
futureList.add(future);
}
// 获取结果
for (Future<Boolean> future : futureList) {
Boolean flag = future.get();
if (flag) {
System.out.println("配货成功");
} else {
System.out.println("配货失败");
}
}
}
/**
* 线程名称
*/
private String name;
/**
* 线程编号
*/
private int num;
public ThreadPoolTest(String name, int num) {
this.name = name;
this.num = num;
}
/**
* @description: 任务
* @author cheng
* @dateTime
@Override
public Boolean call() throws Exception {
System.out.println("====>" + name + "配货开始");
try {
// 模拟配货耗时
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("====>" + name + "配货结束");
// 模拟配货成功和失败
if (num % 2 == 0) {
return true;
}
return false;
}
}
运行结果:
====>Thread-0配货开始
====>Thread-0配货结束
配货成功
====>Thread-1配货开始
====>Thread-1配货结束
配货失败
====>Thread-2配货开始
====>Thread-2配货结束
配货成功
====>Thread-3配货开始
====>Thread-3配货结束
====>Thread-4配货开始
配货失败
====>Thread-4配货结束
配货成功
====>Thread-5配货开始
====>Thread-5配货结束
配货失败
====>Thread-6配货开始
====>Thread-6配货结束
配货成功
====>Thread-7配货开始
====>Thread-7配货结束
配货失败
====>Thread-8配货开始
====>Thread-8配货结束
配货成功
====>Thread-9配货开始
====>Thread-9配货结束
配货失败