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

将定时任务编辑成一个接口

1.定义一个接口 

package com.zsp.quartz.service;

public interface ScheduledService {
    void setInfo();
}

2.定义实现类

package com.zsp.quartz.service.impl;

import com.alibaba.fastjson.JSON;
import com.zsp.quartz.entity.User;
import com.zsp.quartz.service.ScheduledService;
import com.zsp.quartz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ScheduledServiceImpl implements ScheduledService, InitializingBean {
    @Autowired
    UserService userService;

    // 创建线程池
    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    // 1.原始接口方法
    @Override
    @Async
    public void setInfo() {
        for (int i = 0; i < 100; i++) {
            System.out.println("接口的方法" + i);
        }
    }

    // 1.实现InitializingBean的方法
    @Override
    public void afterPropertiesSet() throws Exception {
        executorService.scheduleAtFixedRate(this::scheduleProcessUser, 10, 10, TimeUnit.SECONDS);
    }

    // 2.释放线程池资源的方法 
    // PreDestroy注解:Spring优雅的退出
    @PreDestroy
    public void destroy() {
        try {
            executorService.shutdown();
        } catch (Exception e) {

        }
    }

    // 3.自己定义的线程池中要执行的方法
    public void scheduleProcessUser() {
        while (true) {
            User user = null;
            try {
                user = userService.getById(2);
                Thread.sleep(3000);
                log.info("用户角色信息同步:{}", JSON.toJSONString(user));
            } catch (Exception e) {
                log.error("处理用户角色信息同步异常:{}", JSON.toJSONString(user), e);
            }
        }
    }
}

控制台打印

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架提供了对线程池的支持,可以方便地进行线程池的配置和管理。 在Spring,可以使用`ThreadPoolTaskExecutor`类来创建和配置线程池。首先,需要在Spring配置文件声明一个`ThreadPoolTaskExecutor`的bean,例如: ```xml <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="10" /> <property name="queueCapacity" value="25" /> </bean> ``` 上述配置创建了一个具有5个核心线程、最大10个线程和队列容量为25的线程池。 然后,在代码可以通过注入`ThreadPoolTaskExecutor`来使用线程池,例如: ```java @Autowired private ThreadPoolTaskExecutor taskExecutor; ``` 接下来,可以使用`taskExecutor`对象执行任务,例如: ```java taskExecutor.execute(new Runnable() { public void run() { // 执行具体的任务逻辑 } }); ``` 除了`execute`方法外,`ThreadPoolTaskExecutor`还提供了其他方法,例如`submit`用于提交带有返回值的任务。 需要注意的是,在使用线程池后,应该及时关闭线程池,以释放资源。可以通过调用`destroy()`方法来关闭线程池,或者在Spring配置文件添加一个销毁方法: ```xml <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" destroy-method="shutdown" > <!-- 配置属性 --> </bean> ``` 以上就是在Spring使用线程池的基本方法。希望能对你有所帮助!如果有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值