Thread class sleep method document:
class Thread
{
public static void sleep(long millis) throws InterruptedException
{
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
}
}
Program Code:
class Custom extends Thread
{
public void run()
{
for (int i=1 ; i<=10 ; i++)
{
System.out.println("Custom : " + i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){ }
}
}
}
class Default
{
public static void main(String[] args)
{
Custom th = new Custom();
th.start();
for (int j=1 ; j<=10 ; j++)
{
System.out.println("Default : " + j);
try{
Thread.sleep(1000);
}catch(InterruptedException e){ }
}
}
}
- In single threaded, execution starts @ default thread and ends @ the same thread.
- In multi threaded, any thread can completes the execution while all the threads executing parallel.
class Custom extends Thread
{
public void run()
{
for (int i=1 ; i<=10 ; i++)
{
System.out.println("Custom : " + i);
try{
Thread.sleep(200);
}catch(InterruptedException e){ }
}
System.out.println("Custom thread completed...");
}
}
class Default
{
public static void main(String[] args)
{
Custom th = new Custom();
th.start();
for (int j=1 ; j<=10 ; j++)
{
System.out.println("Default : " + j);
try{
Thread.sleep(1000);
}catch(InterruptedException e){ }
}
System.out.println("Default thread completed...");
}
}