Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

multithreading - inefficient threads in java

I currently have some problems to understand why in some cases, parallelization in Java seems infficient. In the following code, I build 4 identical tasks that are executed using a 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. 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.

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());
        }
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The clue is that you are calling Math.random which uses a single global instance of Random. So, all your 4 threads compete for the one resource.

Using a thread local Random object will make your execution really parallel:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...