Thread.join(毫秒)在java中不准确吗? [英] Thread.join(millisecond) is not accuracy in java?

查看:68
本文介绍了Thread.join(毫秒)在java中不准确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在Java中都知道,Thread.join(long millis)的意思是等待最多毫秒数才能使该线程死亡",但是我发现毫秒数不是很准确,请参见以下代码:

As we all know in java, Thread.join(long millis) means "Waits at most millis milliseconds for this thread to die", but i find the millisecond is not very accuracy, please see the following code:

public class MyThreadTest {
public void invokeTest() {
    long executionTimeLimit = 10;
    Runner rn = new Runner();
    rn.start();
    try {
        long time = System.currentTimeMillis();
        rn.join(executionTimeLimit);
        long l1 = (System.currentTimeMillis() - time);
        System.out.println("execution_time_limit="+executionTimeLimit+" the invoke method time is "+l1+" millisecond");
    } catch (Exception e) {
        //e.printStackTrace();
    }
}
public static void main(String args[]) {
    MyThreadTest mtt = new MyThreadTest();
    mtt.invokeTest();
}
private final class Runner extends Thread {
    public void run()
    {
        //to make the program a bit longer
        int size = 3000;
        String[][] bb = new String[size][size];
        for(int i=0;i<size;i++) 
            for(int j=0;j<size;j++) {
                bb[i][j] = "bbbbbbbbbbb";
        }

    }
}
}

运行多次后,输出日志不相同:

the output log is not same when you running more than one times:

"execution_time_limit = 10调用方法时间为11毫秒" "execution_time_limit = 10调用方法时间为32毫秒" "execution_time_limit = 10调用方法的时间为34毫秒"

"execution_time_limit=10 the invoke method time is 11 millisecond" "execution_time_limit=10 the invoke method time is 32 millisecond" "execution_time_limit=10 the invoke method time is 34 millisecond"

为什么会这样?

推荐答案

当您等待(n)或睡眠(n)且未中断或未通知()ed时,它将至少等待 给定的时间.在join(n)中,两者都是可能的.它会在线程的通知/线程结束时提前唤醒,但之后可以在任何时间唤醒.

When you wait(n) or sleep(n) and it is not interrupted or notify()ed, it waits for at least the time given. In join(n) both is possible. It wakes early on a notify/end of thread, but can wake at any time after that.

在线程可以唤醒和唤醒之间的差异非常大,有监视此类情况的工具. jHiccup 是最好的之一.

The variation is between when a thread could wake and when it does wake is so wide there are tools which monitor such things. jHiccup being one of the best.

线程唤醒的时间取决于负载,也取决于操作系统.这可能导致线程在应有的时间后醒来. MacOS最近的一个问题是,闲置系统的延迟最多可延迟10秒.

When a thread wakes up is dependant onload, but also the OS. This can lead to threads waking long after they should. A recent question for MacOS concerned delays of up to 10 second delay for a idle system.

这是Java无法控制的,它取决于您的操作系统.

This is something Java has no control over, it is down to your OS.

顺便说一句,如果您以微秒为单位查看抖动,则会看到更加丰富多彩的变化/抖动/过程中断.

BTW if you look at jitter on the micro-second level you see much more colourful variations/jitter/interrupts of processes.

微抖动,忙于等待和绑定CPU

这篇关于Thread.join(毫秒)在java中不准确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆