Tuesday, April 27, 2010

Thread.sleep

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Yes thats the kind of explanation they give in javadocs... Couldn't gather much from this.
So here's what it is in common mans language
A thread is like a process(Java gurus pls forgive me), the way we start each process on our machine like a firefox browser, a wordpad, media player etc... Now each of this process appears to be occuring simultaneously. Similar is the case of a thread in java.

You could have multiple threads and each of the threads would execute simultaneously or so it appears to be because of the time sharing it does.

Now getting to the topic of discussion what is Thread.sleep and other questions like isn't it a static method?

It is a static method but it gets the thread that is currently executing to sleep for the specified number of milli seconds.

How does it do it?
Using the concept of TLS or thread local storage. Each thread has a global memory which stores information corresponding to itself. So when Thread.sleep is called the stack which is running the thread is suspended and it waits for the time to complete or for some other method to interrupt it so that it can throw and interrupted exception and continue execution.

Difference between Thread.sleep and Thread.currentThread().sleep()
None. There is no difference between the two. Thread.currentThread returns the current thread that is executing don't confuse it with "this" this refers to object, Thread.currentThread refers to the thread being executed currently.

some more on it will come soon... but currently i'm feeling thread.sleeepy...

No comments: