为什么我的代码在Java中使用多个线程会变慢?

use*_*406 2 java multithreading

所以我有一个程序运行一堆不同的计算,然后在完成所有计算后返回结果.

最初我的代码是同步的,如下所示:

public class MyApplication{

    public static void main(String[] args) {
        doCalculation(1);
        doCalculation(2);
        doCalculation(3);
        doCalculation(4);
        doCalculation(5);
        doCalculation(6);
        doCalculation(7);
        doCalculation(8);

        /* Print result */
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为在新线程中运行这些计算会更有效,所以现在我有类似的东西,

public class MyApplication{
    public static void main(String[] args) {
        List<Thread> threads = new ArrayList<Thread>();
        threads.add(doCalculation(1));
        threads.add(doCalculation(2));
        threads.add(doCalculation(3));
        threads.add(doCalculation(4));
        threads.add(doCalculation(5));
        threads.add(doCalculation(6));
        threads.add(doCalculation(7));
        threads.add(doCalculation(8));

        for(Thread t : threads){
            if(t.isAlive()){
                try{
                    t.join();
                } catch(InterruptedException e) {
                    System.out.println("Error calculating fitness");
                }
            }
        }

        /* Print result */
    }
}
Run Code Online (Sandbox Code Playgroud)

对不起,我是线程的完全初学者.如果我不得不猜测我会假设我已经产生了两个新线程(我的应用程序中有大约50个计算),但任何建议都会非常感激!

ysh*_*vit 5

每个线程都有开始和加入的开销.如果线程所做的工作很重要,那么开销是值得的; 但如果doCalculation很快,那么开销就会压倒它.

一般来说,线程不会让事情变得更快 - 它们只会让更多东西一次性运行.如果每个线程有大量的工作,并且多个线程可以同时以全速运行(这是多个CPU核心帮助的地方),那么这是值得的.

如果每个都doCalculation花费X时间,并且你有8个(因此8T开销,其中T是每个线程的开销量),那么整个程序将花费更长的时间8T > 8TX- 也就是说,如果旋转8个线程的开销大于按顺序执行所有8次计算的工作量.