CompletableFuture详解~异步发起然后...


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;

/**
 * TODO 在此写上类的相关说明.<br>
 * @version 1.0.0 2023年6月28日<br>
 * @see 
 * @since JDK 1.5.0
 */
public class CompletableFutureDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		synGet();
		//thenAccept();
		//asynTaskThensyncGet();
		//thenAcceptAndAllOf();
		//thenAcceptAndWait();
	}

	/**
	 * 异步后直接get--全部同步请求了.
	 */
	static void synGet() {
		Stopwatch stopWatch = Stopwatch.createStarted();
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<10; i++) {
			final String cur = String.valueOf(i);
			try {
				CompletableFuture.supplyAsync(() -> {
					System.out.println(Thread.currentThread().getName() + "--supplyAsync--" + cur);
					if ("5".equals(cur)||"6".equals(cur)||"7".equals(cur)) {
						CommonUtil.sleep(30000L);
					} else {
						CommonUtil.sleep(900L);
					}
					
					return "OK~" + cur;
				})
				.thenAccept(str -> {
					System.out.println(Thread.currentThread().getName()+ "--thenAccept--" + cur + "--" + str);
					sb.append(str);
				})
				// 这里get,会直接阻塞变成了同步.
				.get(2, TimeUnit.SECONDS);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		System.out.println(sb.toString());
		stopWatch.stop();
		System.out.println("synGet-->" + stopWatch.elapsed(TimeUnit.MILLISECONDS));
	}
	
	/**
	 * 异步发起任务,然后同步get.
	 * thenAccept/asynTaskThenGet 差别不大.
	 */
	static void thenAccept() {
		Stopwatch stopWatch = Stopwatch.createStarted();
		Map<Integer, CompletableFuture<Void>> futureMap = new HashMap<>();
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<10; i++) {
			final String cur = String.valueOf(i);
			final CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
				System.out.println(Thread.currentThread().getName() + "--supplyAsync--" + cur);
				if ("5".equals(cur)||"6".equals(cur)||"7".equals(cur)) {
					CommonUtil.sleep(30000L);
				} else {
					CommonUtil.sleep(900L);
				}
				
				return "OK~" + cur;
			})
			.thenAccept(str -> {
				System.out.println(Thread.currentThread().getName()+ "--thenAccept--" + cur + "--" + str);
				sb.append(str);
			});
			futureMap.put(i, future);
		}
		
		// 等待所有任务执行完成.
		for (int i=0; i<10; i++) {
			final CompletableFuture<Void> future = futureMap.get(i);
			try {
				future.get(2, TimeUnit.SECONDS);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(sb.toString());
		stopWatch.stop();
		System.out.println("thenAccept-->" + stopWatch.elapsed(TimeUnit.MILLISECONDS));
	}
	
	/**
	 * 异步发起任务,然后同步get.
	 * thenAccept/asynTaskThenGet 差别不大.
	 */
	static void asynTaskThenGet() {
		Stopwatch stopWatch = Stopwatch.createStarted();
		Map<Integer, CompletableFuture<String>> futureMap = new HashMap<>();
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<10; i++) {
			final String cur = String.valueOf(i);
			final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
				System.out.println(Thread.currentThread().getName() + "--supplyAsync--" + cur);
				if ("5".equals(cur)||"6".equals(cur)||"7".equals(cur)) {
					CommonUtil.sleep(30000L);
				} else {
					CommonUtil.sleep(900L);
				}
				
				return "OK~" + cur;
			});
			futureMap.put(i, future);
		}
		
		// 等待所有任务执行完成.
		for (int i=0; i<10; i++) {
			final CompletableFuture<String> future = futureMap.get(i);
			try {
				final String str = future.get(2, TimeUnit.SECONDS);
				sb.append(str);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(sb.toString());
		stopWatch.stop();
		System.out.println("asynTaskThenGet-->" + stopWatch.elapsed(TimeUnit.MILLISECONDS));
	}
	
	/**
	 * 异步发起任务,然后allOf,再超时get.
	 * 这样所有的任务都是异步执行,也有一个总的超时,只是无法跟踪是哪个任务失败了.
	 * thenAcceptAndAllOf/thenAcceptAndWait 差别不大.
	 */
	static void thenAcceptAndAllOf() {
		Stopwatch stopWatch = Stopwatch.createStarted();
		List<CompletableFuture<Void>> futureList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<10; i++) {
			final String cur = String.valueOf(i);
			try {
				final CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
					System.out.println(Thread.currentThread().getName() + "--supplyAsync--" + cur);
					if ("5".equals(cur)||"6".equals(cur)||"7".equals(cur)) {
						CommonUtil.sleep(30000L);
					} else {
						CommonUtil.sleep(900L);
					}
					
					return "OK~" + cur;
				})
				.thenAccept(str -> {
					System.out.println(Thread.currentThread().getName()+ "--thenAccept--" + cur + "--" + str);
					sb.append(str);
				});
				
				// 添加异步任务.
				futureList.add(future);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			CompletableFuture<?> allFuture = 
					CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()]));
			//这样会一直等待.
			//allFuture.join();
			allFuture.get(3, TimeUnit.SECONDS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("sb=" + sb.toString());
		stopWatch.stop();
		System.out.println("thenAccept-->" + stopWatch.elapsed(TimeUnit.MILLISECONDS));
	}
	
	/**
	 * 全部异步任务发起后再await.
	 * thenAcceptAndAllOf/thenAcceptAndWait 差别不大.
	 */
	static void thenAcceptAndWait() {
		Stopwatch stopWatch = Stopwatch.createStarted();
		final int count = 10;
		CountDownLatch latch = new CountDownLatch(count);
		StringBuilder sb = new StringBuilder();
		for (int i=0; i<count; i++) {
			final String cur = String.valueOf(i);
			CompletableFuture.supplyAsync(() -> {
				System.out.println(Thread.currentThread().getName() + "--supplyAsync--" + cur);
				if ("5".equals(cur)||"6".equals(cur)||"7".equals(cur)) {
					CommonUtil.sleep(30000L);
				} else {
					CommonUtil.sleep(900L);
				}
				
				return "OK~" + cur;
			}).thenAccept(str -> {
				System.out.println(Thread.currentThread().getName()+ "--thenAccept--" + cur + "--" + str);
				sb.append(str);
				latch.countDown();
			});
		}
		
		// 等待所有任务执行完成.
		try {
			latch.await(3, TimeUnit.SECONDS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(sb.toString());
		stopWatch.stop();
		System.out.println("thenAcceptAndWait-->" + stopWatch.elapsed(TimeUnit.MILLISECONDS));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值