springboot项目如何支持(Future、ThreadPoolTaskExecutor、CountDownLatch、Callable、Runnable)对异步任务的支持和处理

 

参考:

https://juejin.cn/post/6844903774985650183

https://blog.youkuaiyun.com/weixin_43491745/article/details/107665756  学习借鉴和快捷键记录上

创建线程的方式

  • 通过继承Thread类
public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("线程已执行。。。");
    }
}
  • 实现接口
public class MyThread2 implements Runnable {

    @Override
    public void run() {
        System.out.println("基于实现Runnable接口的多线程");
    }
}

Callable的使用

 

Future的使用

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

FutureTask为其最终具体的实现类;

Future提供了三种功能:

  1. 判断任务是否完成;
  2. 能够中断任务;
  3. 能够获取任务执行结果。

ThreadPoolTaskExecutor 线程池Task

也就是说通过线程池的方式不仅解决了针对Runnable多线程的实现类,无法获取结果的问题(广义上),也可以使用Callable的实现类获取执行结果的;

execute执行一个线程,需要返回值的
//不需要返回值的
@Override
public void execute(Runnable task) {
	Executor executor = getThreadPoolExecutor();
	try {
		executor.execute(task);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}

//需要返回值的
@Override
public Future<?> submit(Runnable task) {
	ExecutorService executor = getThreadPoolExecutor();
	try {
		return executor.submit(task);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}

//Callable带返回值的
@Override
public <T> Future<T> submit(Callable<T> task) {
	ExecutorService executor = getThreadPoolExecutor();
	try {
		return executor.submit(task);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}

示例(1)异步任务,同步阻塞

import cn.hutool.core.date.DateUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("xxxx-");
        //配置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(5);
        //配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(10);
        //配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(100);
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                System.out.println("丢弃");
            }
        });
        threadPoolTaskExecutor.initialize();
        int taskNum = 10;
        CountDownLatch latch = new CountDownLatch(taskNum);
        for (int i = 0; i < taskNum; i++) {
            final int taskId = i;
            threadPoolTaskExecutor.execute(() -> {
                try {
                    System.out.printf("线程号: %s, 多线程名称: %s,当前子任务需要执行 %s 秒, start at %s\n", taskId, Thread.currentThread().getName(),
                            taskId * taskId, DateUtil.now());
                    TimeUnit.SECONDS.sleep(taskId * taskId);
                    System.out.printf("task: %s, thread: %s,当前子任务执行 %s 秒【任务处理完毕】, end at %s\n", taskId, Thread.currentThread().getName()
                            ,taskId * taskId, DateUtil.now());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            });
        }
        System.out.println("主程序执行。。。马上等待子线程执行结束后继续");
        System.out.println("主线程等待中....");
        latch.await();
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值