Sleep method in java

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


\begin{lstlisting}
class TestSleepMethod1 extends Thread{
public void run(){
...
...new TestSleepMethod1();
\par
t1.start();
t2.start();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
1
1
2
2
3
3
4
4
\end{lstlisting}

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:


\begin{lstlisting}
public class TestThreadTwice1 extends Thread{
public void r...
... t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
\end{lstlisting}

Test it Now
\begin{lstlisting}
running
Exception in thread ''main'' java.lang.IllegalThreadStateException
\end{lstlisting}

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.


\begin{lstlisting}
class TestCallRun1 extends Thread{
public void run(){
Sys...
....run();//fine, but does not start a separate call stack
}
}
\end{lstlisting}

Test it Now


\begin{lstlisting}
Output:running...
\end{lstlisting}

Lets see the other examples


\begin{lstlisting}
class TestCallRun2 extends Thread{
public void run(){
for...
...Run2 t2=new TestCallRun2();
\par
t1.run();
t2.run();
}
}
\end{lstlisting}

Test it Now


\begin{lstlisting}
Output:1
2
3
4
5
1
2
3
4
5
\end{lstlisting}

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.