Page 162 - CTS - CSA TP - Volume 2
P. 162
COMPUTER SOFTWARE APPLICATION - CITS
Explanation:
1 SleepExample Class:
• This class extends the Thread class, indicating that instances of this class can be executed as separate
threads.
2 run() Method:
• The run() method overrides the run() method of the Thread class, defining the behavior of the thread when
it starts.
• Inside the run() method:
• It prints “Thread is running...” to indicate that the thread has started its execution.
• It enters a loop to simulate some work by printing the thread ID along with a sequence number (Value) from
0 to 4.
• After printing each value, the thread calls Thread.sleep(500) to pause its execution for 500 milliseconds
(0.5 seconds).
• The sleep() method may throw an InterruptedException, so it’s enclosed within a try-catch block to handle
this exception gracefully.
3 main() Method:
• This method serves as the entry point of the program.
• Inside main():
• An instance of the SleepExample class named sleepThread is created.
• The start() method is invoked on sleepThread to begin the execution of the thread.
4 Output:
• When the program is executed:
• The thread starts its execution and prints “Thread is running...”.
• Then, in a loop, it prints the thread ID along with values from 0 to 4, with a 500-millisecond delay between
each value.
• After printing all values, the thread completes its execution.
5 Exception Handling:
• The sleep() method can throw an InterruptedException if the thread is interrupted while sleeping.
• In the catch block, the program prints “Thread interrupted” to indicate that the thread’s sleep was interrupted.
• Depending on the application’s requirements, the exception can be handled or propagated further for
handling at another level.
This program demonstrates how to use the sleep() method to introduce delays in the execution of threads, which
is useful for scenarios where you need to control timing or simulate processing delays.
Output:
147
CITS : IT & ITES - Computer Software Application - Exercise 104