Java CompletableFuture.allOf() 、thenApplyAsync()、thenRun()等使用

本文探讨了Java中的安全上下文管理,通过SecurityContextHolder进行Authentication的获取与设置。接着介绍了线程池ThreadPoolTaskExecutor的配置,包括核心线程数、最大线程数、存活时间、队列容量及拒绝策略。还展示了如何使用CompletableFuture进行异步任务的并发执行,利用allOf方法等待所有任务完成,并演示了任务的先后顺序调用。内容涵盖了并发控制、线程池和异步编程的关键知识点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
SecurityContextHolder.getContext().setAuthentication(authentication);

线程池使用:

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 1. 当一个任务被提交到线程池时,首先查看线程池的核心线程是否都在执行任务,否就选择一条线程执行任务,是就执行第二步。
 * 2. 查看核心线程池是否已满,不满就创建一条线程执行任务,否则执行第三步。
 * 3. 查看任务队列是否已满,不满就将任务存储在任务队列中(SynchronousQueue同步队直接执行第四步),否则执行第四步。
 * 4. 查看线程池是否已满,不满就创建一条线程执行任务,否则就按照策略处理无法执行的任务。
 */
@Configuration
public class ThreadPoolTaskConfig {

    @Bean
    public ThreadPoolTaskExecutor executor(){
    	ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //此方法返回可用处理器的虚拟机的最大数量; 不小于1
        int core = Runtime.getRuntime().availableProcessors();
        threadPoolTaskExecutor.setCorePoolSize(core);//设置核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(core*2 + 1);//设置最大线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(30);//除核心线程外的线程存活时间
        threadPoolTaskExecutor.setQueueCapacity(40);//如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
        threadPoolTaskExecutor.setThreadNamePrefix("project-module-name-thread-execute");//线程名称前缀
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
        return threadPoolTaskExecutor;
    }
}

allOf使用:

package java8;


//import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.logging.Logger;
/**
 * 
 * @Description:TODO(CompletableFuture.allOf使用)   
 * @author: HeShengjin
 * @date:   2021年5月7日 下午4:22:51    
 * @Copyright:
 */
public class AllOfTest {
	private final static Logger log = Logger.getLogger(AllOfTest.class.getName());
	//使用自己的线程池
    private final static ThreadPoolExecutor executorServe = new ThreadPoolExecutor(3,
            Runtime.getRuntime().availableProcessors() * 3,
            5, 
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000));
    //随机数
    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        //现在时间
    	Instant start = Instant.now();
        
        List<CompletableFuture<String>> list = new ArrayList<CompletableFuture<String>>();
        
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
        list.add(CompletableFuture.supplyAsync(() -> getData(), executorServe));
                
        CompletableFuture.allOf(list.toArray(new CompletableFuture[list.size()])).join();

        log.info(String.format("********全部执行完毕,总耗时:%s ********", (ChronoUnit.SECONDS.between(start, Instant.now()))));
        //打印结果
        list.parallelStream().forEach((cf)->{
        	log.info(cf.join());
        });
        executorServe.shutdownNow();
    }

    /**
     * 
     * @Description: TODO(随机模拟请求耗时)   
     * @param: @return      
     * @return: String      
     * @throws
     */
    private static String getData() {
        int anInt = random.nextInt(10);
        String info = String.format("----当前线程%s,随机数:%s秒----",Thread.currentThread().getName(), anInt);
        log.info(info);
        try {
            TimeUnit.SECONDS.sleep(anInt);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "【结束返回】"+info;

    }
}



在这里插入图片描述
先后顺序调用:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * 
 * @Description:TODO(CompletableFuture先后调用顺序)   
 * @author: HeShengjin
 * @date:   2021年5月8日 下午1:25:53    
 * @Copyright:
 */
public class CompletableFutureTest {
	//使用自己的线程池
	//或者: import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
	//@Resource
    //ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private final static ThreadPoolExecutor executorServe = new ThreadPoolExecutor(3,
            Runtime.getRuntime().availableProcessors() * 3,
            5, 
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000));
    
		 public static void main(String[] args) throws InterruptedException, ExecutionException {

			    CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return "第1个耗时的任务执行完毕!【有参数】";
			    }, executorServe);

			    CompletableFuture<String> cf2 = cf1.thenApplyAsync(s -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return s + ";第2个耗时的任务执行完毕!【有参数】";
			    }, executorServe);
			    
			    CompletableFuture<String> cf3 = cf2.thenApplyAsync(s -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return s + ";第3个耗时的任务执行完毕!【有参数】";
			    }, executorServe);
			    
			    //链式调用先后顺序结束
			    System.out.println(cf3.get());

			    //不要写前面的返回值
			    cf3.thenRun(() -> {
			    	System.out.println("第3个耗时的任务执行完毕!【无参数】");
			    });
		}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值