线程与CompletableFuture [英] Thread vs CompletableFuture

查看:114
本文介绍了线程与CompletableFuture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接将代码传递给线程vs使用CompletableFuture有什么好处?

What is the advantage of passing code directly to thread vs using CompletableFuture instead?

Thread thread = new Thread(() -> {do something});
thread.start();

VS

CompletableFuture<Void> cf1 =  
     CompletableFuture.runAsync(() -> {do something}); 


推荐答案

CompletableFuture.runAsync(。 ..)在forkJoin-Pool中运行Runnable,其中被管理,而 new Thread()创建一个新的你必须管理的线程。

CompletableFuture.runAsync(...) runs the Runnable in the forkJoin-Pool which is managed, while new Thread() creates a new thread which you have to manage.

被管理是什么意思,它是预先分配的线程在JVM中共享。当runnable完成后,该线程可以重用于其他runnables。这样可以更好地利用资源,特别是当线程实例化是一项昂贵的操作时 - 不仅需要分配对象,还需要一些额外的非堆内存 - 线程堆栈。

What does "is managed" mean, it's pre-allocated and the threads are shared in the JVM. When the runnable is completed, the thread can be reused for other runnables. This makes better usage of resources, especially as thread instantiation is an expensive operation - not only the object, but also some extra non-heap memory - the thread stack - has to be allocated.

这篇关于线程与CompletableFuture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆