别说你不知道什么是异步编程的Future!
你就是写了个假异步
先聊聊线程池的提交方式
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
//execute(Runnable command)方法。没有返回值
executor.execute(() -> {
System.out.println("关注why技术");
});
Thread.currentThread().join();
}
}
提交执行 Runnable 类型的任务。 提交执行 Callable 类型的任务。
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
Future<String> future = executor.submit(() -> {
System.out.println("关注why技术");
return "这次一定!";
});
System.out.println("future的内容:" + future.get());
Thread.currentThread().join();
}
}
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
Future<?> future = executor.submit(() -> {
System.out.println("关注why技术");
});
System.out.println("future的内容:" + future.get());
Thread.currentThread().join();
}
}
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
AtomicInteger atomicInteger = new AtomicInteger();
Future<AtomicInteger> future = executor.submit(() -> {
System.out.println("关注why技术");
//在这里进行计算逻辑
atomicInteger.set(5201314);
}, atomicInteger);
System.out.println("future的内容:" + future.get());
Thread.currentThread().join();
}
}
只有主动调用 get 方法去获取值,但是有可能值还没准备好,就阻塞等待。 任务处理过程中出现异常会把异常隐藏,封装到 Future 里面去,只有调用 get 方法的时候才知道异常了。
Guava 的 Future
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture<String> listenableFuture = executor.submit(() -> {
System.out.println(Thread.currentThread().getName()+"-女神:我开始化妆了,好了我叫你。");
TimeUnit.SECONDS.sleep(5);
return "化妆完毕了。";
});
listenableFuture.addListener(() -> {
try {
System.out.println(Thread.currentThread().getName()+"-future的内容:" + listenableFuture.get());
} catch (Exception e) {
e.printStackTrace();
}
}, executor);
System.out.println(Thread.currentThread().getName()+"-等女神化妆的时候可以干点自己的事情。");
Thread.currentThread().join();
}
}
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture<String> listenableFuture = executor.submit(() -> {
System.out.println(Thread.currentThread().getName()+"-女神:我开始化妆了,好了我叫你。");
TimeUnit.SECONDS.sleep(5);
return "化妆完毕了。";
});
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
@Override
public void onSuccess(@Nullable String result) {
System.out.println(Thread.currentThread().getName()+"-future的内容:" + result);
}
@Override
public void onFailure(Throwable t) {
System.out.println(Thread.currentThread().getName()+"-女神放你鸽子了。");
t.printStackTrace();
}
});
System.out.println(Thread.currentThread().getName()+"-等女神化妆的时候可以干点自己的事情。");
Thread.currentThread().join();
}
}
ListenableFuture<String> listenableFuture = executor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "-女神:我开始化妆了,好了我叫你。");
TimeUnit.SECONDS.sleep(5);
throw new Exception("男神约我看电影,就不和你吃饭了。");
});
加强版的Future - CompletableFuture
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "-女神:我开始化妆了,好了我叫你。");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "化妆完毕了。";
});
completableFuture.whenComplete((returnStr, exception) -> {
if (exception == null) {
System.out.println(Thread.currentThread().getName() + returnStr);
} else {
System.out.println(Thread.currentThread().getName() + "女神放你鸽子了。");
exception.printStackTrace();
}
});
System.out.println(Thread.currentThread().getName() + "-等女神化妆的时候可以干点自己的事情。");
Thread.currentThread().join();
}
}
public class JDKThreadPoolExecutorTest {
public static void main(String[] args) throws Exception {
CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "-女神:我开始化妆了,好了我叫你。");
throw new RuntimeException("男神约我看电影了,我们下次再约吧,你是个好人。");
}).handleAsync((result, exception) -> {
if (exception != null) {
System.out.println(Thread.currentThread().getName() + "-女神放你鸽子了!");
return exception.getCause();
} else {
return result;
}
}).thenApplyAsync((returnStr) -> {
System.out.println(Thread.currentThread().getName() + "-" + returnStr);
return returnStr;
});
System.out.println(Thread.currentThread().getName() + "-等女神化妆的时候可以干点自己的事情。");
Thread.currentThread().join();
}
}
更多精彩推荐 ☞互联网不相信学渣 ☞漫画:设计模式之 “外观模式” ☞微软回应“断供中国”谣言;斗鱼回应与虎牙合并;Android 11 Beta 3 发布| 极客头条 ☞图解Transformer,读完这篇就够了 ☞三次改变世界、却被无情出局的程序员 ☞地方政府争夺试点,互联网巨头参与测试,央行数字货币指日可待 点分享 点点赞 点在看
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号
随时掌握互联网精彩
随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 这本书,智利总统带到秘鲁的会见厅 7971153
- 2 药监局:百雀羚不存在违规行为 7971280
- 3 胖东来:员工不许靠父母买房买车 7888915
- 4 世界互联网大会有哪些新看点? 7769268
- 5 一个金镯子省出1200元 金价真跌了 7618419
- 6 医院CT等收费将执行新规 7563159
- 7 19岁孤儿被骗到郑州4天没吃没喝 7438713
- 8 29岁抗癌博主“一只羊吖”去世 7331477
- 9 梁靖崑不敌张本智和 无缘8强 7213863
- 10 科技与文化融合的“赛博”水乡 7169921