简体   繁体   English

Java多线程-return语句花费太多时间

[英]Java Multithreading - return statement taking too much time

In multithreading (Executor framework), the sum total of all time-prints within x() method is not matching to the total time printed by doPerform. 在多线程(Executor框架)中,x()方法中所有时间打印的总和与doPerform打印的总时间不匹配。 And this difference keeps on growing with increasing number of threads in threadpool (goes upto 20 secs). 随着线程池中线程数量的增加(最多20秒),这种差异会继续增长。 Can someone please figure out why? 有人可以找出原因吗? And is there any way to decrease time taken to return from x method? 有什么方法可以减少从x方法返回的时间吗?
I have tested it with: 我已经测试过:

a) 500 submissions to executor (poolsize =100) a)500份提交给执行人(poolsize = 100)
b) 500 submissions to executor (poolsize =300) b)500个提交给执行者的文件(poolsize = 300)
c) 300 submissions to executor (poolsize =100) c)300个提交给执行者的文件(poolsize = 100)

public void x() {
    long startTime = System.currentTimeMillis();
    for (long l = 0; l <= 10000000; l++) {
        if (l % 1000000 == 0) {
            System.out.println("Thread id: "
                    + Thread.currentThread().getId() + "\t"
                    + (System.currentTimeMillis() - startTime));
            startTime = System.currentTimeMillis();
        }
    }
}

public void doPerform() {
    long startTime = System.currentTimeMillis();
    x();
    System.out.println("Thread id: " + Thread.currentThread().getId()
            + "\t" + (System.currentTimeMillis() - startTime));
}

That's expected. 那是意料之中的。 You have 100 or 300 parallel threads being executed, and only 1, 2 or 4 cores to execute them all (unless you're running this on a giant super computer). 您有100或300个并行线程正在执行,只有1,2或4个内核可以全部执行(除非您在巨型超级计算机上运行)。 This means that each thread is assigned some CPU time, then some other thread, then some other thread, etc. giving the illusion of parallel execution. 这意味着为每个线程分配了一些CPU时间,然后分配了另一个线程,然后分配了其他线程,等等,给人以并行执行的错觉。 But in reality, instructions of various threads are interlaced and executed sequentially. 但是实际上,各种线程的指令是交织并顺序执行的。

So, you could have a thread A 's startTime computation in doPerform() executed, and then the thread could be replaced by several other ones one on the CPU. 因此,您可以在doPerform()执行线程AstartTime计算,然后可以在CPU上将该线程替换为其他几个线程。 A number of milliseconds could elapse before the thread scheduler reassigns A to a CPU and the startTime computation in x() is executed. 在线程调度程序将A重新分配给CPU并执行x()startTime计算之前,可能要经过几毫秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM