不带返回值
int threads = 10; ExecutorService executorService = Executors.newFixedThreadPool(threads); CountDownLatch countDownLatch = new CountDownLatch(supplierArray.size()); for(int i = 0; i<supplierArray.size(); i++){ JSONObject jsonObject = supplierArray.getJSONObject(i); Long supplierId = jsonObject.getLong("SupplierId"); String supplierName = jsonObject.getString("Supplier"); String supplierNumber = jsonObject.getString("SupplierNumber"); executorService.execute(new SuppSiteRunable(countDownLatch, supplierId, supplierNumber, supplierName, serverDomain, authToken)); log.info("countDownLatch "+ countDownLatch.getCount()); } try { countDownLatch.await(); executorService.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); log.error(e.getMessage(), e); }
带返回值
int threads = 40; List<FutureTask<Map<String, Object>>> futureTasks = new ArrayList<>(); ExecutorService executorService = Executors.newFixedThreadPool(threads); CountDownLatch countDownLatch = new CountDownLatch(list.size()); for(int i=0 ; i<list.size(); i++){ Map<String, Object> map = list.get(i); String loginid = (String)map.get("loginid"); String token = (String)map.get("token"); String lastname = (String)map.get("lastname"); String workcode = (String)map.get("workcode"); String email = (String)map.get("email"); FutureTask<Map<String, Object>> futureTask = new FutureTask<>(new BpmTaskCallable(loginid, token, lastname, email, workcode)); futureTasks.add(futureTask); //提交任务到线程池 executorService.submit(futureTask); } int index =1; for (FutureTask<Map<String, Object>> futureTask: futureTasks){ Map<String, Object> map =futureTask.get(); List<UfBpmTaskHeader> bpmList = (List<UfBpmTaskHeader>)map.get("bpmList"); countDownLatch.countDown(); log.info("剩余未处理数量 {}", countDownLatch.getCount()); } executorService.shutdown();
使用SpringBoot 多线程
定义线程池
@Bean("ProjectCCWExecutor") public ThreadPoolTaskExecutor ProjectCCWExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数:线程池创建时候初始化的线程数 executor.setCorePoolSize(10); // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 // executor.setMaxPoolSize(20); // 缓冲队列:用来缓冲执行任务的队列 // executor.setQueueCapacity(500); // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁 executor.setKeepAliveSeconds(60); executor.setAllowCoreThreadTimeOut(true); // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 executor.setThreadNamePrefix("do-project-ccw-"); // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程) executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); executor.initialize(); return executor; }
使用,PS,调用方法和执行函数不要放在同一个类中
@Async("ProjectCCWExecutor") public void saveTaskByProject(CountDownLatch countDownLatch,String projectId) throws Exception { try{ erpPmProjectsCcwService.saveDataByProjectId(projectId, response); }catch (Exception e){ XxlJobLogger.log("projectId {} 更新项目及任务数据异常,{}", projectId, e.getMessage()); }finally { countDownLatch.countDown(); XxlJobLogger.log("当前剩余未处理项目数量 {} ",countDownLatch.getCount()); } }
CountDownLatch countDownLatch = new CountDownLatch(list.size()); for(Map<String, Object> map :list){ pmProjectsSaveCcwByPrjNum.saveTaskByProject(countDownLatch, map.get("PROJECT_ID").toString()); } countDownLatch.await();
带返回值(转:https://blog.csdn.net/lihaiyong92/article/details/117254607)
// 异步执行代码 @Service("asyncExecutorTest") public class AsyncExecutorTest { // 异步执行的方法, 注解内为自定义线程池类名 @Async("localBootAsyncExecutor") public Future<Integer> test1(Integer i) throws InterruptedException { Thread.sleep(100); System.out.println("@Async 执行: " + i); return new AsyncResult(i); } // 这里使用其它方式调用,详见后面的 service3 方法 public Integer test2(Integer i) throws InterruptedException { Thread.sleep(100); System.out.println(" excute.run 执行: " + i); return i; } }
// 业务 service @Service("asyncExcutorService") public class AsyncExcutorService { @Autowired AsyncExecutorTest asyncExecutorTest; @Autowired Executor localBootAsyncExecutor; // 测试 无返回值异步执行 public void service1(){ System.out.println("service1 执行----->"); for (int i = 0; i < 50; i++) { try { asyncExecutorTest.test1(i); } catch (InterruptedException e) { System.out.println("service1执行出错"); } } System.out.println("service1 结束----->"); } // 测试 有返回值异步执行 public void service2(){ long l = System.currentTimeMillis(); System.out.println("service2 执行----->"); List<Future> result = new ArrayList<>(); try { for (int i = 0; i < 300; i++) { Future<Integer> integerFuture = asyncExecutorTest.test1(i); result.add(integerFuture); } for (Future future : result) { System.out.println(future.get()); } } catch (InterruptedException | ExecutionException e) { System.out.println("service2执行出错"); } System.out.println("service2 结束----->" + (System.currentTimeMillis() - l)); } // 测试 有返回值异步执行 public void service3(){ long l = System.currentTimeMillis(); List<Integer> result = new ArrayList<>(); try { System.out.println("service3 执行----->"); int total = 300; CountDownLatch latch = new CountDownLatch(total); for (int i = 0; i < total; i++) { final int y = i; localBootAsyncExecutor.execute(() -> { try { result.add(asyncExecutorTest.test2(y)); } catch (InterruptedException e) { System.out.println("service3执行出错"); } finally { latch.countDown(); } }); } latch.await(); } catch (InterruptedException e) { System.out.println("service3执行出错"); } System.out.println("service3 结束----->" + (System.currentTimeMillis() - l)); } }