Lab 3 Sleep Method 456CSS-3
Lab 3 Sleep Method 456CSS-3
Lab 3
Sleep Method in Thread/ Multithread
456CSS-3
PARALLEL AND DISTRIBUTED SYSTEMS
Objective:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
Output:thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread object.
So you need to explicitly create Thread class object. We are passing the object of your class
that implements Runnable so that your class run() method may execute.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Parameters
millis − This is the length of time to sleep in milliseconds.
Return Value
This method does not return any value.
Exception
InterruptedException − if any thread has interrupted the current thread. The interrupted status of
the current thread is cleared when this exception is thrown.
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time, the thread scheduler picks up another thread and so on.
/*
Pause Thread Using Sleep Method Example
This Java example shows how to pause currently running thread using
sleep method of Java Thread class.
*/
/*
* To pause execution of a thread, use
* void sleep(int milliseconds) method of Thread class.
*
* This is a static method and causes the suspension of the thread
* for specified period of time.
*
* Please note that, this method may throw InterruptedException.
*/
System.out.println(i);
/*
* This thread will pause for 1000 milliseconds after
* printing each number.
*/
Thread.sleep(1000);
}
}
catch(InterruptedException ie){
System.out.println("Thread interrupted !" + ie);
}
}
}
/*
Output of this example would be
Print number after pausing for 1000 milliseconds
0
1
2
3
4
*/