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));
}
}
CompletableFuture详解~异步发起然后...
最新推荐文章于 2024-01-21 01:02:02 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)