SpringBoot多线程在项目中的实际应用
1、项目中实际运用,自建线程池,批量执行异步任务
public void test() throws ExecutionException, InterruptedException {
Integer count = 10;
// 批量创建时采用多线程
ExecutorService executorService = new ThreadPoolExecutor(count, count,
10L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new ThreadFactoryBuilder()
.setNameFormat("excute-pool-%d")
.build(),
new ThreadPoolExecutor.AbortPolicy());
CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 1; i <= count; i++) {
Runnable runnable = () -> {
try {
Thread.sleep(5000);
//执行任务逻辑代码,比如调用第三方接口创建任务啥的。
System.out.println("任务:" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
};
executorService.submit(runnable);
}
try {
//任务执行完,才继续往下走,如果不用管任务是否执行完,把该代码注释掉即可
//具体要结合业务场景使用
countDownLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
e.printStackTrace();
}
executorService.shutdown();
System.out.println(".......");
}
2、批量异步查询-CompletableFuture的使用
CompletableFuture是java8推出的一个非常简便的多线程写法。2.1 几种创建方式
1、runAsync()是没返回结果的,supplyAsync()可以指定返回结果。2、使用没有指定Executor(线程池)的方法时,内部使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。
3、如果所有CompletableFuture共享一个线程池,那么一旦有任务执行一些很慢的 I/O 操作,就会导致线程池中所有线程都阻塞在 I/O 操作上,从而造成线程饥饿,进而影响整个系统的性能。所以,强烈建议你要根据不同的业务类型创建不同的线程池,以避免互相干扰。
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
public static void main(String[] args) throws ExecutionException, InterruptedException {
Runnable runnable = () -> System.out.println("无返回结果异步任务");
CompletableFuture.runAsync(runnable);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(5000);
System.out.println("有返回值的异步任务1");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello World";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(