Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

sleep - How to suspend a java thread for a small period of time, like 100 nanoseconds?

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.

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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...