线程池在项目中的使用

第一种方式

1、自定义一个线程池配置类
@Configuration
@EnableAsync   // 开启多线程
public class ThreadPoolConfig {
    @Bean("taskExecuter")
    public ThreadPoolTaskExecutor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(20);
        // 配置队列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        // 设置线程活跃时间
        executor.setKeepAliveSeconds(60);
        //设置默认线程名称
        executor.setThreadNamePrefix("多线程---");
        // 等待所有任务结束后在关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 执行初始化
        executor.initialize();
        return executor;
    }
}
2、自定义一个service异步处理类
@Component
public class ThreadService {
    @Autowired
    private ThreadTestDao testDao;
    @Async("taskExecuter")
    public void updateThread(ThreadTest test) {
        testDao.updateThreadData(test);
        try {
            Thread.sleep(5000);
            System.out.println("更新已完成。。。。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
3、使用
@RestController
@RequestMapping("/thread")
public class ThreadTestController {
    @Autowired
    private ThreadTestService threadTestService;
    // 异步服务
    @Autowired
    private ThreadService threadService;
    @PostMapping("/t1")
    public void thread1(@RequestBody ThreadTest test) {
        threadTestService.insertThreadTest(test);
        // 对于其他不影响主业务流程的业务逻辑可以用线程池   异步操作  
        threadService.updateThread(test);
        System.out.println("插入成功。。。。");
    }
}

第二种方式

1、引入上面创建线程池类
@Autowired
private ThreadPoolTaskExecutor taskExecuter;

@PostMapping("/t2")
    public void thread2(@RequestBody ThreadTest test) throws ExecutionException, InterruptedException {
        threadTestService.deleteThreadTest(test);
        // 对于其他不影响主业务流程的业务逻辑可以用线程池   异步操作
        List<Future> futures = new ArrayList<>();
        //定义计数器
        CountDownLatch latch = new CountDownLatch(50);
        List<ThreadTest> threadTests = new ArrayList<>();
        ThreadTest newTest = null;
        for (int i = 0; i < 50; i++) {
            newTest = new ThreadTest();
            BeanUtils.copyProperties(test,newTest);
            newTest.setUserName(test.getUserName()+i);
            newTest.setUserCount(i);
            threadTests.add(newTest);
        }
         for (ThreadTest threadTest : threadTests) {
            Future<String> future = taskExecuter.submit(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName());
                    threadTestService.insertThreadTest(threadTest);
                    return "插入成功";
                } catch (InterruptedException e) {
                    log.info("失败信息",e);
                    return "";
                } finally {
                    latch.countDown();
                }
            });
            futures.add(future);
        }
        System.out.println("删除成功。。。。");
        //等待子任务执行完毕
        latch.await();
        for (Future future : futures) {
            System.out.println(future.get());
        }
    }
=====================
// 统计异常数量可以使用
AtomicInteger atomicInteger = new AtomicInteger();  // 多线程环境下,具有原子性

第三种方式

@PostMapping("/t3")
    public void thread3(@RequestBody ThreadTest test) throws ExecutionException, InterruptedException {
        CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
            ThreadTest threadTest = testDao.findThread(1);
            return threadTest;
        }, taskExecuter);
        CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
            ThreadTest threadTest = testDao.findThread(2);
            return threadTest;
        }, taskExecuter);
        // 等待完成
        CompletableFuture.allOf(future1,future2).get();
        System.out.println(future1.get());
        System.out.println(future2.get());
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最好的期待,未来可期

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值