线程睡眠时间过长 [英] Thread sleeps for too long

查看:229
本文介绍了线程睡眠时间过长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的程序,发现我的线程对我来说太快了,无法运行JVisualVM,标记我要监视的应用程序,插入并查看线程.然后,我让他们入睡.现在,著名的工具将其报告为仅处于睡眠状态(或几乎仅处于睡眠状态).即使他们工作.这就引出了一个问题:为什么?!

I wrote a simple program and noticed that my threads are too fast for me to run JVisualVM, mark which app I want to monitor, plug in and look at threads. I then made them sleep. And noticed tools now report them as only sleeping (or almost only sleeping). Even though they work. This begs the question: why?!

    new Thread(() -> {
        while(true) {
            System.out.println("not sleeping");
            try {
                Thread.sleep(0,1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "not sleeping!").start();

该线程应该休眠1纳秒,但请看一下JVisualVM的报告方式:

This thread should sleep for 1 nanosecond, yet take a look at how it's reported by JVisualVM:

运行57s后,它报告运行时间为5s,休息时间为睡眠-是错误还是我的理解错误?

After running for 57s it reports 5s running time and rest as sleeping - a bug or is my understanding wrong?

不仅仅是JVisualVM:

It's not just JVisualVM:

$ while true; do jstack 8277 | grep -A 2 not; done              [% 20:34:27]
"not sleeping!" #10 prio=5 os_prio=0 tid=0x00007f5ea82d1000 nid=0x2078 waiting on condition [0x00007f5e917c6000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)

jstack也仅偶尔将此线程报告为RUNNING.我希望使用不同的比例,所以请帮助我理解.

jstack also only occasionally reports this thread as RUNNING. I'd expect different proportions, so please help me understand.

推荐答案

您不能期望睡眠时间短至1纳秒.当您请求睡眠时,您将执行任务切换,这需要一些时间才能安排回来,特别是在您有其他进程/线程的情况下.因此,如果线程的工作量很低,那么它可能最终会花费大部分时间在睡眠状态.

You can't expect to sleep for as short as 1 nanosecond. When you request to sleep you will do a task switch and it make take some time until it can be scheduled back, especially if you have other processes/threads. So if the workload of the thread is very low then it may end up spending most of the time sleeping.

您的睡眠时间也可能会在某一层向上舍入为系统时间粒度的倍数.至少在某些Java实现中,nanos参数

It is also probable that your sleeping time is rounded up at some layer to a multiple of system's time granularity. At least in some Java implementations the nanos argument is mostly ignored.

这篇关于线程睡眠时间过长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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