当前位置: 首页 > news >正文

test111

step3:多线程task

首先,实现两个UserService和AsyncUserService两个服务接口:

package com.example.demospringboot.service;public interface UserService {void checkUserStatus();
}
package com.example.demospringboot.service.impl;import com.example.demospringboot.bean.User;
import com.example.demospringboot.service.UserService;
import com.example.demospringboot.dao.UserMapper;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Slf4j
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic void checkUserStatus() {List<User> AllUsers = userMapper.findAllUsers();for (User u : AllUsers) {// System.out.println(ThreadUtils.getThreadName() + ": " + u);log.info("{}", u);}};
}
package com.example.demospringboot.service;public interface AsyncUserService {void checkUserStatus();
}
package com.example.demospringboot.service.impl;import com.example.demospringboot.task.AsyncTasks;
import com.example.demospringboot.service.AsyncUserService;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AsyncUserServiceImpl implements AsyncUserService {@Autowiredprivate AsyncTasks asyncTasks;@Overridepublic void checkUserStatus() {asyncTasks.doTaskOne("1");asyncTasks.doTaskOne("2");asyncTasks.doTaskOne("3");};
}

然后用两个WorkManager进行管理:

package com.example.demospringboot.workmanager;import com.example.demospringboot.service.UserService;
import com.example.demospringboot.utils.ThreadUtils;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class WorkManager {private static final ThreadPoolTaskExecutor EXECUTOR_POOL =ThreadUtils.getThreadPool(ThreadUtils.EXECUTOR_POOL_PREFIX);@Autowiredprivate UserService userService;public void startExecutor() {EXECUTOR_POOL.execute(new Executor(userService));}static class Executor implements Runnable {private UserService userService;public Executor(UserService userService) {this.userService = userService;}@Overridepublic void run() {while (true) {userService.checkUserStatus();// sleep 1sThreadUtils.sleepUtil(1000L);}}}
}
package com.example.demospringboot.workmanager;import com.example.demospringboot.service.AsyncUserService;
import com.example.demospringboot.utils.ThreadUtils;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class AsyncWorkManager {private static final ThreadPoolTaskExecutor ASYNC_EXECUTOR_POOL =ThreadUtils.getThreadPool(ThreadUtils.ASYNC_EXECUTOR_POOL_PREFIX);@Autowiredprivate AsyncUserService asyncUserService;public void startSyncExecutor() {ASYNC_EXECUTOR_POOL.execute(new AsyncExecutor(asyncUserService));}static class AsyncExecutor implements Runnable {private AsyncUserService asyncUserService;public AsyncExecutor(AsyncUserService asyncUserService) {this.asyncUserService = asyncUserService;}@Overridepublic void run() {while (true) {asyncUserService.checkUserStatus();// sleep 1sThreadUtils.sleepUtil(1000L);}}}
}

用到的task类和thread工具类如下:

package com.example.demospringboot.task;import com.example.demospringboot.utils.ThreadUtils;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Component
public class AsyncTasks {public static Random random = new Random();// @Async注解中的参数就是异步任务的线程池@Async("taskExecutor")public CompletableFuture<String> doTaskOne(String taskNo){log.info("开始任务:{}", taskNo);long start = System.currentTimeMillis();ThreadUtils.sleepUtil(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务:{},耗时:{} 毫秒", taskNo, end - start);return CompletableFuture.completedFuture("任务完成");}}
package com.example.demospringboot.utils;import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Repository;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;@Repository
public class ThreadUtils {public static final int MAX_POOL_SIZE = 2;public static final String EXECUTOR_POOL_PREFIX = "exe-" + MAX_POOL_SIZE + "-";public static final String ASYNC_EXECUTOR_POOL_PREFIX = "async-exe-" + MAX_POOL_SIZE + "-";public static final String ASYNC_TASK_POOL_PREFIX = "async-task-" + MAX_POOL_SIZE + "-";// 自定义AsyncTask线程池@Beanpublic ThreadPoolTaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(MAX_POOL_SIZE);executor.setMaxPoolSize(MAX_POOL_SIZE);executor.setQueueCapacity(MAX_POOL_SIZE);executor.setKeepAliveSeconds(0);executor.setThreadNamePrefix(ASYNC_TASK_POOL_PREFIX);// 如果添加到线程池失败,那么主线程会自己去执行该任务executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());return executor;}// 启动Executor的线程池public static ThreadPoolTaskExecutor getThreadPool(String threadNamePrefix) {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(MAX_POOL_SIZE);executor.setMaxPoolSize(MAX_POOL_SIZE);executor.setQueueCapacity(MAX_POOL_SIZE);executor.setKeepAliveSeconds(0);executor.setThreadNamePrefix(threadNamePrefix);executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());executor.initialize();return executor;}public static void sleepUtil(long millis) {try {Thread.sleep(millis);} catch (InterruptedException e) {System.out.println(e);}}
}

主类如下:

package com.example.demospringboot;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.cache.annotation.EnableCaching;import com.example.demospringboot.workmanager.WorkManager;
import com.example.demospringboot.workmanager.AsyncWorkManager;@EnableCaching
@EnableAsync
@SpringBootApplication
@MapperScan(value = {"com.example.demospringboot.dao"})
public class DemospringbootApplication implements CommandLineRunner {@Autowiredprivate WorkManager workManager;@Autowiredprivate AsyncWorkManager asyncWorkManager;public static void main(String[] args) {SpringApplication.run(DemospringbootApplication.class, args);}@Overridepublic void run(String... strings) {//workManager.startExecutor();asyncWorkManager.startSyncExecutor();}
}
http://www.lryc.cn/news/113361.html

相关文章:

  • 17. Spring 事务
  • 【C# 基础精讲】运算符和表达式
  • 【搜索】DFS连通性模型
  • 项目优化后续 ,手撸一个精简版VUE项目框架!
  • 【深度学习笔记】TensorFlow 基础
  • 面试题-springcloud中的负载均衡是如何实现的?
  • flink的ProcessWindowFunction函数的三种状态
  • day50-springboot+ajax分页
  • Win7 专业版Windows time w32time服务电脑重启后老是已停止
  • 全网最强,接口自动化测试-token登录关联实战总结(超详细)
  • OLAP ModelKit Crack,ADO.NET和IList
  • 4 三组例子,用OpenCV玩转图像-AI-python
  • 计算机网络-三种交换方式
  • 03 制作Ubuntu启动盘
  • 【JavaSE】String类中常用的字符串方法(超全)
  • Bootload U-Boot分析
  • 以公益之行,筑责任之心——2023年中创算力爱心公益助学活动
  • 【机器学习】处理样本不平衡的问题
  • Android前沿技术?Jetpack如何?
  • 为react项目添加开发/提交规范(前端工程化、eslint、prettier、husky、commitlint、stylelint)
  • 小研究 - MySQL 数据库安全加固技术的研究(一)
  • linux安装redis带图详细
  • MySql——数据库常用命令
  • 如何通过 WordPress 数据库启用插件?【进不去后台可用】
  • 芯片热处理设备 HTR-4立式4寸快速退火炉
  • 小研究 - 基于 MySQL 数据库的数据安全应用设计(一)
  • mysql转sqlite3
  • 在linux中使用 ./configure 时报错
  • 【LeetCode 算法】Reverse String 反转字符串
  • linux sysctl.conf 常用参数配置