Java并发编程 优化多任务查询接口
阅读原文时间:2023年08月25日阅读:3
@RestController
@RequestMapping("/api")
public class TestController {

    @Resource
    private SourceService sourceService;

    @Resource
    private StudentService studentService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private Executor executor;

    @PostMapping("/multithreading")
    public List<Object> multithreading() throws InterruptedException {
        //记录开始时间
        long startingTime = System.currentTimeMillis();
        //线程计数器 定义为3
        CountDownLatch downLatch = new CountDownLatch(3);

        //防止并发操作情况下出现 并发修改异常,单线程不存在这个问题,CopyOnWriteArrayList底层使用Lock锁,性能可以被保证
        List<Object> list = new CopyOnWriteArrayList<>();

        //线程1: 查询 source表 并添加到list
        executor.execute(() -> {
            list.add(sourceService.findAll());
            downLatch.countDown();// 线程计数器-1
        });
        //线程2: 查询 teacher表 并添加到list
        executor.execute(() -> {

            list.add(teacherService.findAll());
            downLatch.countDown();// 线程计数器-1
        });
        //线程3: 查询 teacher表 并添加到list
        executor.execute(() -> {
            list.add(studentService.findAll());
            downLatch.countDown();// 线程计数器-1
        });

        downLatch.await();//如果计数到达零,则释放所有等待的线程
        //响应结果 取决最后一个线程执行时间
        long endingTime = System.currentTimeMillis();

        System.out.println("多线程耗时:" + (endingTime - startingTime) + "ms");
        return list;
    }

    @PostMapping("/singleThread")
    public List<Object> singleThread() {
        //记录开始时间
        long startingTime = System.currentTimeMillis();
        List<Object> list = new ArrayList<>();
        //执行查询
        list.add(sourceService.findAll());
        list.add(teacherService.findAll());
        list.add(studentService.findAll());
        //结束时间
        long endingTime = System.currentTimeMillis();

        System.out.println("单线程耗时:" + (endingTime - startingTime) + "ms");
        return list;
    }
}

多线程响应结果平均: 14.8ms

单线程响应结果平均: 31.4ms

ps:在任务量多的情况下 多线程速度会越来越显著