The sleep() method of Thread class is used to sleep a thread for the specified amount of time. The Thread class provides two methods for sleeping a thread:
Example of sleep method in java
Output:
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.
A thread can't be executed twisce. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. Let's understand it by the example given below:
Test it Now
What if we call run() method directly instead start() method? Each thread starts in a separate call stack. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
Test it Now
Lets see the other examples
Test it Now
As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.