常用的多线程类
创建池
ExecutorService executor = Executors.newFixedThreadPool(4);
Executors工程类,可以提交任务。executor.submit(Callable
记得关闭池shutdown。
springboot对上述操作已经进行了封装
Spring Boot 中的线程池,这也太好用了! - 腾讯云开发者社区-腾讯云 (tencent.com)
有返回值的异步操作Callable
//Executors创建的队列容量允许的太多,将会导致oom,所以采用ThreadPoolTaskExecutor、或ThreadPoolExecutor 进行队列容量限制
// ExecutorService executor = Executors.newFixedThreadPool(4);
// ExecutorService executor = new ThreadPoolExecutor(10, 10,60L, TimeUnit.SECONDS, new ArrayBlockingQueue(10));
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setKeepAliveSeconds(60);
executor.setQueueCapacity(40);
executor.initialize();
Future<Integer> submit = executor.submit(() -> {
Thread.sleep((int) 0 + (int) (Math.random() * 2));
System.out.println(1);
return 1;
});
Future<Integer> submit1 = executor.submit(() -> {
Thread.sleep((int) 0 + (int) (Math.random() * 2));
System.out.println(2);
return 2;
});
/*
// submit.get();
// submit1.get(); 都不进行get数据就是不确定的顺序异步的。
*/
/*
submit.get();
// submit1.get(); 进行submit数据.get,2,3
*/
System.out.println(3);
executor.shutdown();
同时计算成功即返回数据CompletableFuture
//每个线程做的事情
CompletableFuture<String> C1 = CompletableFuture.supplyAsync(() -> {
return queryCourse("1", "2");
});
CompletableFuture<String> C2 = CompletableFuture.supplyAsync(() -> {
return queryCourse("2", "3");
});
//监听多个线程有一个成功,不阻塞,没返回也向下执行.
CompletableFuture<Object> voidCompletableFuture = CompletableFuture.anyOf(C1, C2);
voidCompletableFuture.thenAccept(res -> {
System.out.println(res);
});
(82条消息) SpringBoot 使用 CompletableFuture 实现非阻塞异步编程_流放深圳的博客-CSDN博客_springboot异步非阻塞
spring 封装的ListenableFuture 对象
executor.submitListenable()线程池中添加任务。通过调用addCallback方法可以写回调函数完成对正确与异常的数据进行处理。
setMaxPoolSize(2);
e.setKeepAliveSeconds(60);
e.setQueueCapacity(Integer.MAX_VALUE);
e.initialize();
e.submitListenable(() -> {
// 休息 5 秒,模拟工作的情况
TimeUnit.SECONDS.sleep(5);
// 通过抛出 RuntimeException 异常来模拟异常
// throw new RuntimeException("出现异常");
return 1;
}).addCallback(data -> System.out.println("success,result = " + data), ex -> System.out.println("**异常信息**:" + ex));
e.shutdown();
标签:常用,get,System,submit,CompletableFuture,executor,println,多线程
From: https://www.cnblogs.com/bullbat/p/16802483.html