[英]Right way to execute 2 independent tasks in Java
I have 2 independent tasks to execute.我有 2 个独立的任务要执行。 I need the result of Task1 first followed by task2.
我首先需要Task1的结果,然后是task2。
Which of the below 2 ways is better in terms of number of threads and performance(if at all) and why?就线程数和性能(如果有的话)而言,以下两种方式中哪一种更好,为什么? Will there be any performance difference between the 2 methods?
两种方法之间会有任何性能差异吗?
Method1:方法1:
1. Execute Task1 & Task2 asynchronously by submitting them to ExecutorService
2. Get the results by calling future1.get() followed future2.get()
Method2:方法2:
1. Execute task2 asynchronously by submitting it to ExecutorService.
2. Execute Task1 on main thread
3. Get the result of task2 by calling future2.get()
The first is better from human point of view:从人类的角度来看,第一个更好:
The second is better from jvm point of view:从 jvm 的角度来看,第二个更好:
But generally over optimize the code is not a good idea if the resulting code is less human readable.但是,如果生成的代码可读性较差,通常过度优化代码并不是一个好主意。 My tip is:
我的建议是:
Don't optimize the code if not needed.
如果不需要,不要优化代码。
I would think method 1 is preferable.我认为方法1更可取。 You are kicking off both tasks, then telling the compiler that you have nothing else to do until both tasks complete.
您正在启动这两个任务,然后告诉编译器在这两个任务完成之前您无事可做。 Once both tasks are complete you can proceed.
两项任务都完成后,您可以继续。 You leave any decisions/optimisations on how to run the tasks to the JVM which is best positioned to make those decisions.
您将有关如何运行任务的任何决定/优化留给最适合做出这些决定的 JVM。
I would suspect that there is little difference with respect to threads, processing time, etc. to either approach once the code is compiled and optimised by the JVM - the 'work' to be done is the same either way.我怀疑一旦代码由 JVM 编译和优化,两种方法在线程、处理时间等方面几乎没有区别——无论哪种方式,要完成的“工作”都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.