赞
踩
- public static void main(String[] args) {
- //定义线程池
- ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
- //信号量定义
- CountDownLatch countDownLatch = new CountDownLatch(2);
- //提交异步任务1
- Future<Integer> future1 = threadPoolExecutor.submit(() -> {
- try {
- System.out.println("任务1获取连接");
- Thread.sleep(1000);
- System.out.println("任务1开始处理查询结果");
- return 1 ;
- } catch (Exception e){
- System.out.println("任务1catch="+e.getMessage());
- return null ;
- }finally {
- //信号量递减
- countDownLatch.countDown();
- System.out.println("任务1归还连接");
- }
- });
- //提交异步任务2
- Future<Integer> future2 = threadPoolExecutor.submit(() -> {
- try {
- System.out.println("任务2获取连接");
- Thread.sleep(20000);
- System.out.println("任务2开始处理查询结果");
- return 2 ;
- } catch (Exception e){
- System.out.println("任务2catch="+e.getMessage());
- return null ;
- }finally {
- //信号量递减
- countDownLatch.countDown();
- System.out.println("任务2归还连接");
- }
- });
-
- //等待都执行完成
- try {
- countDownLatch.await(2, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println("*****************************开始打印执行结果*********************************");
-
- if(future1.isDone()){
- Integer integer = null;
- try {
- integer = future1.get();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("任务1执行结果="+integer);
- }else {
- System.out.println("任务1执行结果=null");
- future1.cancel(true);
- }
-
- if(future2.isDone()){
- Integer integer = null;
- try {
- integer = future2.get();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("任务2执行结果="+integer);
- }else {
- System.out.println("任务2执行结果=null");
- future2.cancel(true);
- }
- }
- 任务1获取连接
- 任务2获取连接
- 任务1开始处理查询结果
- 任务1归还连接
- *****************************开始打印执行结果*********************************
- 任务1执行结果=1
- 任务2执行结果=null
- 任务2catch=sleep interrupted
- 任务2归还连接
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。