[英]inefficient threads in java
I currently have some problems to understand why in some cases, parallelization in Java seems infficient. 我目前有一些问题需要理解为什么在某些情况下,Java中的并行化似乎效率不高。 In the following code, I build 4 identical tasks that are executed using a ThreadPool.
在下面的代码中,我构建了4个使用ThreadPool执行的相同任务。
On my Core i5 (2 core, 4 thread), if I set the number of workers to 1, the computer needs around 5700ms and use 25% of the processor. 在我的Core i5(2核,4线程)上,如果我将工作器数设置为1,则计算机需要大约5700ms并使用25%的处理器。 If I set the number of workers to 4, then I observe 100% of CPU usage but... the time of computation is the same: 5700ms, while I expect it to be 4 times lower.
如果我将工作器数量设置为4,那么我会观察100%的CPU使用率,但是...计算时间是相同的:5700ms,而我预计它会低4倍。
Why? 为什么? Is it normal?
这是正常的吗?
(Of course my real task is more complicated, but the example seems to reproduce the problem). (当然我的真正任务更复杂,但这个例子似乎重现了这个问题)。 Thank you by advance for your answers.
提前谢谢你的答案。
Here is the code: 这是代码:
public class Test {
public static void main(String[] args) {
int nb_workers=1;
ExecutorService executor=Executors.newFixedThreadPool(nb_workers);
long tic=System.currentTimeMillis();
for(int i=0; i<4;i++){
WorkerTest wt=new WorkerTest();
executor.execute(wt);
}
executor.shutdown();
try {
executor.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(System.currentTimeMillis()-tic);
}
public static class WorkerTest implements Runnable {
@Override
public void run() {
double[] array=new double[10000000];
for (int i=0;i<array.length;i++){
array[i]=Math.tanh(Math.random());
}
}
}
}
The clue is that you are calling Math.random
which uses a single global instance of Random
. 线索是您正在调用
Math.random
,它使用单个全局Random
实例。 So, all your 4 threads compete for the one resource. 所以,你所有的4个线程都争夺一个资源。
Using a thread local Random
object will make your execution really parallel: 使用线程本地
Random
对象将使您的执行真正并行:
Random random = new Random();
double[] array = new double[10000000];
for (int i = 0; i < array.length; i++) {
array[i] = Math.tanh(random.nextDouble());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.