I was wondering do all programs have a unnamed thread by default?

For example, if i have a very basic program, can i put Thread.sleep(int) anywhere in it and it will make the program sleep for a set amount of time?

Recommended Answers

All 5 Replies

I was wondering do all programs have a unnamed thread by default?

For example, if i have a very basic program, can i put Thread.sleep(int) anywhere in it and it will make the program sleep for a set amount of time?

Every program has a default thread, a single sequential flow of control of the program. You can't use the sleep method to make that thread sleep for a specific amount of time. The value that is passed to the sleep method is not normally int but it is long What I meant is it is not Thread.sleep(int) but it is Thread.sleep(long). That value actually represents milliseconds

Oh, my bad. It was more of an example.

But basically, can you make a thread sleep even if you haven't declared a Thread anywhere.

For example Thread.sleep(20);

I threw together a quick program to test if sleep works

class boring 
{
    public static void main(String[] args)
    {
        System.out.println("This should " + System.currentTimeMillis());
        try
        {

        Thread.sleep(25);
        }
        catch(InterruptedException e)
        {
        }
        System.out.println("Be 25 millis later "+ System.currentTimeMillis());
    }
}

and the difference between the 2 values was either 16 or 31 (give or take one or two milliseconds) and as far as I'm concerned this means that thread.sleep() doesn't work unless you have declared a new thread.

And did you try it with larger values? Run this with various values for the sleep time

long start = 0;
for (int i=0; i<20; i++){
    start = System.currentTimeMillis();
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
    }
    System.out.println((System.currentTimeMillis() - start));
}

And the doc on currentTimeMillis() has the following to say

public static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

Ta DAHH! I get 500 every time. Thanks a lot, I was leaving room for error in my original code, but when it returned differences below what i was sleeping the thread for, i got worried.

Thanks a lot, now I know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.