为什么创建更多的线程而不是更少的线程数量,总的运行时间会变慢

时间:2018-07-18 23:56:03

标签: java multithreading

我正在研究多线程以正确理解它。因此,我试图测试“正在创建的线程数”如何影响给定任务的总运行时间。

class Worker implements Runnable {

    private int id;

    public Worker(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println("Starting thread ->" + Thread.currentThread().getName() + " with ID: " + id);
        System.out.println("Finishing thread ->" + Thread.currentThread().getName() + " with ID: " + id);
    }
}

public class App {

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        ExecutorService threadPool;
        Map<Integer, Long> performanceMetric = new HashMap<>();
        for (int j = 3; j > 0; j -= 1) {
            long begin = System.currentTimeMillis();

所以在这里,我通过在循环上分配一个高值来创建最大数量的线程。我只是简单地使用循环中的“ j”值并将其分配给执行程序。

            threadPool = Executors.newFixedThreadPool(j);
            System.out.println("\nTotal threads created: " + j);
            app.performService(threadPool);
            threadPool.shutdown();

在计算总耗时之前,请确保先关闭执行程序(线程池)。

            threadPool.awaitTermination(1, TimeUnit.SECONDS);

这里正在计算完成任务所需的总时间。除非所有任务都完成,否则不会计算总时间。

            long totalTime = (System.currentTimeMillis() - begin);
            System.out.println("Is the ThreadPool shutdown: " + (threadPool.isTerminated() ? "Yes" : "No"));
            performanceMetric.put(j, totalTime);
            System.out.println("\nTotal time elapsed when using " + j + " threads is " + totalTime + " milliseconds");
        }
        Set<Integer> keySet = performanceMetric.keySet();
        for (int key : keySet) {
            System.out.println("\nSUMMARY\n\nTotal time elapsed when using " + key + " threads is "
                    + performanceMetric.get(key) + " milliseconds");
        }
    }

    public void performService(ExecutorService threadPool) {
        for (int i = 0; i < 5; i++) {
            threadPool.submit(new Worker(i));
        }
    }
}

上述程序的输出如下

开始输出

Total threads created: 3
Starting thread ---pool-1-thread-1 with ID: 0
Starting thread ---pool-1-thread-3 with ID: 2
Starting thread ---pool-1-thread-2 with ID: 1
Finishing thread ---pool-1-thread-3 with ID: 2
Finishing thread ---pool-1-thread-1 with ID: 0
Finishing thread ---pool-1-thread-2 with ID: 1
Starting thread ---pool-1-thread-3 with ID: 3
Starting thread ---pool-1-thread-2 with ID: 4
Finishing thread ---pool-1-thread-3 with ID: 3
Finishing thread ---pool-1-thread-2 with ID: 4
Is the ThreadPool shutdown: Yes

Total time elapsed when using 3 threads is 4 milliseconds

Total threads created: 2
Starting thread ---pool-2-thread-1 with ID: 0
Finishing thread ---pool-2-thread-1 with ID: 0
Starting thread ---pool-2-thread-1 with ID: 2
Finishing thread ---pool-2-thread-1 with ID: 2
Starting thread ---pool-2-thread-2 with ID: 1
Finishing thread ---pool-2-thread-2 with ID: 1
Starting thread ---pool-2-thread-1 with ID: 3
Finishing thread ---pool-2-thread-1 with ID: 3
Starting thread ---pool-2-thread-2 with ID: 4
Finishing thread ---pool-2-thread-2 with ID: 4
Is the ThreadPool shutdown: Yes

Total time elapsed when using 2 threads is 0 milliseconds

Total threads created: 1
Starting thread ---pool-3-thread-1 with ID: 0
Finishing thread ---pool-3-thread-1 with ID: 0
Starting thread ---pool-3-thread-1 with ID: 1
Finishing thread ---pool-3-thread-1 with ID: 1
Starting thread ---pool-3-thread-1 with ID: 2
Finishing thread ---pool-3-thread-1 with ID: 2
Starting thread ---pool-3-thread-1 with ID: 3
Finishing thread ---pool-3-thread-1 with ID: 3
Starting thread ---pool-3-thread-1 with ID: 4
Finishing thread ---pool-3-thread-1 with ID: 4
Is the ThreadPool shutdown: Yes

Total time elapsed when using 1 threads is 0 milliseconds

Total time elapsed when using 1 threads is 0 milliseconds

Total time elapsed when using 2 threads is 0 milliseconds

Total time elapsed when using 3 threads is 4 milliseconds

最终输出

我很惊讶一个或两个线程的执行速度比三个线程快。有人可以解释一下吗。

1 个答案:

答案 0 :(得分:1)

在每个试验中,您所做的工作并不是恒定不变的,而是通过不同数量的线程进行划分。您只是在创建不同数量的线程。您创建,启动和监视的线程越多,花费的时间就越长。

这就是您的多线程开销;只有当您的工作量受益于并行化时,这才是值得的。在此示例中,不是。