• java中线程池的使用+优雅的spring释放资源


    1.定义一个接口 

    1. package com.zsp.quartz.service;
    2. public interface ScheduledService {
    3. void setInfo();
    4. }

    2.定义实现类

    1. package com.zsp.quartz.service.impl;
    2. import com.alibaba.fastjson.JSON;
    3. import com.zsp.quartz.entity.User;
    4. import com.zsp.quartz.service.ScheduledService;
    5. import com.zsp.quartz.service.UserService;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.springframework.beans.factory.InitializingBean;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.scheduling.annotation.Async;
    10. import org.springframework.stereotype.Service;
    11. import javax.annotation.PreDestroy;
    12. import java.util.concurrent.Executors;
    13. import java.util.concurrent.ScheduledExecutorService;
    14. import java.util.concurrent.TimeUnit;
    15. @Service
    16. @Slf4j
    17. public class ScheduledServiceImpl implements ScheduledService, InitializingBean {
    18. @Autowired
    19. UserService userService;
    20. // 创建线程池
    21. private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    22. // 1.原始接口方法
    23. @Override
    24. @Async
    25. public void setInfo() {
    26. for (int i = 0; i < 100; i++) {
    27. System.out.println("接口的方法" + i);
    28. }
    29. }
    30. // 1.实现InitializingBean的方法
    31. @Override
    32. public void afterPropertiesSet() throws Exception {
    33. executorService.scheduleAtFixedRate(this::scheduleProcessUser, 10, 10, TimeUnit.SECONDS);
    34. }
    35. // 2.释放线程池资源的方法
    36. // PreDestroy注解:Spring优雅的退出
    37. @PreDestroy
    38. public void destroy() {
    39. try {
    40. executorService.shutdown();
    41. } catch (Exception e) {
    42. }
    43. }
    44. // 3.自己定义的线程池中要执行的方法
    45. public void scheduleProcessUser() {
    46. while (true) {
    47. User user = null;
    48. try {
    49. user = userService.getById(2);
    50. Thread.sleep(3000);
    51. log.info("用户角色信息同步:{}", JSON.toJSONString(user));
    52. } catch (Exception e) {
    53. log.error("处理用户角色信息同步异常:{}", JSON.toJSONString(user), e);
    54. }
    55. }
    56. }
    57. }

    控制台打印

  • 相关阅读:
    牛客网---活动运营刷题笔记
    动态链接库(一)--动态链接库简介
    trident-java使用
    1panel + Pbootcms 设置伪静态规则
    远程桌面登录Windows云服务器报错0x112f
    VUE右键菜单 vue-contextmenujs的使用
    Java ~ Executor ~ LinkedBlockingQueue【源码】
    网页制作课作业基于HTML+CSS+JavaScript+jquery仿慕课网教学培训网站设计实例 企业网站制作
    开淘宝店保证金怎么交
    一个类在什么时候会被加载
  • 原文地址:https://blog.csdn.net/m0_55627541/article/details/133674706