Java可调用:比单线程进程花费的时间更长

Java可调用:比单线程进程花费的时间更长,java,multithreading,callable,java-threads,Java,Multithreading,Callable,Java Threads,我有下面的示例代码 import java.util.*; import java.lang.*; import java.io.*; import java.util.concurrent.*; public class CalculationThread implements Callable<Long> { public Long call() throws Exception { long k=0L; for(int i=0;i&l

我有下面的示例代码

import java.util.*;
import java.lang.*;
import java.io.*;

import java.util.concurrent.*;
public class CalculationThread implements Callable<Long> {

    public Long call() throws Exception {
        long k=0L;
        for(int i=0;i<100000;i++){
            for(int j=0;j<50;j++){
                k=i+j;
            }
        }
        return k;
    }
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        long startTime = System.nanoTime();
        for(int lo=0;lo<5000;lo++){
            Future<Long> result = executorService.submit(new CalculationThread());

            try {
                Long l = result.get();
            } catch (Exception e) {
                result.cancel(true);
            }

        }
        long endTime = System.nanoTime();
        System.out.println("Using threads took "+(endTime - startTime) + " ns");

        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.SECONDS);

        long k=0L;
        startTime = System.nanoTime();
        for(int lo=0;lo<5000;lo++){
            for(int i=0;i<100000;i++){
                for(int j=0;j<50;j++){
                    k=i+j;
                }
            }

        }
        endTime = System.nanoTime();
        System.out.println("Generally it takes "+(endTime - startTime) + " ns");

    }
}

可以注意到,第二行几乎是常量,而线程版本变化很大。为什么会这样?可以采取什么措施来降低可变性?请让我知道我是否在做一些愚蠢的事情,因为我是Java多线程新手

Future#在你的通话结束前获得阻塞。因此,主线程向池提交一个可调用文件,然后坐在那里等待它完成,然后再提交下一个。您有创建池的四个线程的开销,然后您有线程和对象创建之间的上下文切换,您在其中创建可调用项(在丢弃可调用项时进行垃圾收集),然后您不同时执行任何工作


在使用池的版本更快的地方,您如何获得数字是令人费解的。当我在本地运行此程序时(顺便说一句,制作MVCE做得很好,我可以复制和粘贴而不做任何更改,并且可以正常工作),我得到的线程池部分的数字始终较高,大约是单线程代码的3倍。

在可用的4个线程中添加了4个初始线程,并将剩余的4996个操作添加到线程池中,这在比较短时间的总执行时间
~149ms(一般执行)
时效率不高。线程在
time>2s min
中非常有用,并尝试减少线程池中的QUE数量。感谢您的回复。我不知道我这边发生了什么。我理解你的观点,直到callable结束。你能提供一个例子/一个链接来说明如何处理这种情况,在这种情况下,我可以看到实际的时间减少吗?@SandipanBhattacharyya:那得晚一点,现在不行。您可以使用runnables,而不必等待输出。或者使用completionservice,在您提交完所有任务后再执行这些任务。当然会尝试。谢谢您的帮助!
Using threads took 101960490 ns
Generally it takes 143107865 ns
Using threads took 245339720 ns
Generally it takes 149699885 ns