简体   繁体   English

Java8中的lambda表达式是否执行多线程?

[英]Are lambda-expressions in Java8 executed multi threaded?

In Java8, lambda expressions were introduced. 在Java8中,引入了lambda表达式 This question is about when parallel lambdas are executed. 这个问题是关于何时执行并行lambda。

Before Java8, Callable -classes were one way to execute multiple threads at one time. 在Java8之前, Callable -classes是一次执行多个线程的一种方法。 Callables can be used with Executor -classes to be executed. 可以将Callables与Executor -classes一起使用来执行。 Let's assume I am using a Fixed Thread Pool , using 3 as number of active processing tasks. 假设我使用固定线程池 ,使用3作为活动处理任务的数量。 And let's assume I have 8 tasks. 我们假设我有8个任务。 Fixed Thread Pool would start first three tasks, and as one finishes, next task is started, until all 8 tasks are finished. 固定线程池将启动前三个任务,并在完成后,启动下一个任务,直到完成所有8个任务。

What would happen, if I implement my tasks as Java8-lambdas? 如果我将我的任务实现为Java8-lambdas,会发生什么? Would all 8 be started at once? 全部8个会立刻开始吗? Or sequentially? 还是顺序? Or in any clever way? 还是以任何聪明的方式?

In special, are they running in the same thread as the caller (without using an Exeuctor)? 特别是,它们是否与调用者在同一个线程中运行(不使用Exeuctor)? By their nature, I guess lambdas could be executed in another thread easily. 就其本质而言,我猜lambdas可以很容易地在另一个线程中执行。

Runnable r = () -> System.out.println("hello");

is equivalent to 相当于

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("hello")
    }
};

And it doesn't change anything to how a runnable is executed. 并且它不会改变runnable的执行方式。 If you submit your runnable to a thread pool, then the thread pool will execute it, whatever you used to create your runnable: a lambda, an anonymous class, or a top-level class. 如果将runnable提交给线程池,则线程池将执行它,无论您使用什么创建runnable:lambda,匿名类或顶级类。 In the end, what you define is an instance of Runnable, and that's the only thing which matters. 最后,你定义的是Runnable的一个实例,这是唯一重要的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM