java中的低效线程

我目前有一些问题需要理解为什么在某些情况下,Java中的并行化似乎效率低下。 在下面的代码中,我构建了4个使用ThreadPool执行的相同任务。

在我的Core i5(2核,4线程)上,如果我将工作器数设置为1,则计算机需要大约5700ms并使用25%的处理器。 如果我将worker的数量设置为4,那么我会观察100%的CPU使用率,但是…计算的时间是相同的:5700ms,而我预计它会低4倍。

为什么? 这是正常的吗?

(当然我的真正任务更复杂,但这个例子似乎重现了这个问题)。 提前谢谢你的答案。

这是代码:

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()); } } } } 

线索是您正在调用Math.random ,它使用单个全局Random实例。 所以,你所有的4个线程都争夺一个资源。

使用线程本地Random对象将使您的执行真正并行:

 Random random = new Random(); double[] array = new double[10000000]; for (int i = 0; i < array.length; i++) { array[i] = Math.tanh(random.nextDouble()); }