如何暂停java线程一小段时间,如100纳秒? [英] How to suspend a java thread for a small period of time, like 100 nanoseconds?

查看:572
本文介绍了如何暂停java线程一小段时间,如100纳秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Thread.sleep()可以让java线程暂停一段时间,比如某些毫秒和某些纳秒。但问题是这个函数的调用也会导致开销。

I know Thread.sleep() can make a java thread suspend for a while, like certain milliseconds and certain nanoseconds. But the problem is the invocation of this function also causes overhead.

例如,如果我想要一个线程暂停100纳秒,我会调用 Thread.sleep(0,100)。这个过程的全部成本是 invocation_cost + 100 nanosceonds ,这可能比我想要的要大得多。我怎么能避免这个问题,实现我的目的呢?

For example, if I want a thread to suspend for 100 nanoseconds, and I call Thread.sleep(0, 100). The whole cost for this process is invocation_cost + 100 nanosceonds, which may be much larger the what I want. How could I avoid this problem, and achieve my purpose?

我需要这个的原因是我想离线模拟。我描述了任务的执行时间;现在我想通过在同一时间段暂停一个线程来模拟这个执行时间。

The reason I need this is that I want to do simulation offline. I profiled the execution time of a task; Now I want to simulate this execution time by suspending a thread in the same time period.

谢谢!

推荐答案

睡眠的粒度通常受线程调度程序的中断周期的约束。在Linux中,这个中断周期在最近的内核中通常为1ms。在Windows中,调度程序的中断周期通常在10或15毫秒左右

The granularity of sleeps is generally bound by the thread scheduler's interrupt period. In Linux, this interrupt period is generally 1ms in recent kernels. In Windows, the scheduler's interrupt period is normally around 10 or 15 milliseconds

如果我必须暂停线程的时间少于此,我通常会使用繁忙的等待

If I have to halt threads for periods less than this, I normally use a busy wait

编辑:我怀疑你在jrockit + solaris上会得到最好的结果。 Windows框上的数字很糟糕。

EDIT: I suspect you'll get best results on jrockit + solaris. The numbers on a windows box are terrible.

@Test
public void testWait(){
    final long INTERVAL = 100;
    long start = System.nanoTime();
    long end=0;
    do{
        end = System.nanoTime();
    }while(start + INTERVAL >= end);
    System.out.println(end - start);
}

这篇关于如何暂停java线程一小段时间,如100纳秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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