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个耗时的任务执行完毕!【无参数】");
});
}
}