inefficient threads in java

前端 未结 1 1003
我寻月下人不归
我寻月下人不归 2020-12-11 06:49

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

相关标签:
1条回答
  • 2020-12-11 07:45

    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());
    }
    
    0 讨论(0)
提交回复
热议问题