1 获得结果和触发计算
1.1 获取结果
-
public T get()
-
public T get(long timeout,TimeUnit unit)
-
public T join() --->和get一样的作用,只是不需要抛出异常
-
public T getNow(T valuelfAbsent) --->计算完成就返回正常值,否则返回备胎值(传入的参数),立即获取结果不阻塞
1.2 主动触发计算
-
public boolean complete(T value) ---->是否打断线程方法立即返回括号值
1.3 案例实操
前面文章已经介绍过get() 和 get(long timeout,TimeUnit unit) 使用方法了,这里就直接略过。
1.3.1 join()
和get一样的作用,只是不需要抛出异常
public static void main(String[] args) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "abc";
});
System.out.println(completableFuture.get());
System.out.println(completableFuture.join());
}
1.3.2 getNow(T valuelfAbsent)
public static void main(String[] args) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "abc";
});
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 如果CompletableFuture线程没有计算的时间 小于 主线程 那么 结果是 XXXX
* 反之 则是 CompletableFuture 线程的计算结果
*/
System.out.println(completableFuture.getNow("xxxx"));
}
1.3.3 public boolean complete(T value)
是否打断线程方法立即返回括号值
public static void main(String[] args) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "abc";
});
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(completableFuture.complete("completevalue")+"\t"+completableFuture.join());
}
标签:JUC,get,编程,completableFuture,TimeUnit,CompletableFuture,public,sleep
From: https://www.cnblogs.com/mangoubiubiu/p/17963779