Page 161 - CTS - CSA TP - Volume 2
P. 161
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 104 : Use major thread methods
Objectives
At the end of this exercise you shall be able to
• know the Major Thread Methods in Java
• develop Java programs using Thread Methods.
Requirements
Tools/Materials
• PC / laptop with windows OS
• SDK software
• Test editor (Visual studio/ subline/ notepad)
Procedure
1 sleep(long millis) Method:
• Purpose: Pauses the execution of the current thread for the specified number of milliseconds.
• Syntax:Thread.sleep(long millis)
• Parameters:
millis: The duration, in milliseconds, for which the thread should sleep.
• Use Case: Used to introduce delays or pauses in the execution of a thread.
public class SleepExample extends Thread {
public void run() {
System.out.println(“Thread is running...”);
// Simulate some work
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + “ Value “ + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(“Thread interrupted”);
// Handle the exception or propagate it further if necessary
}
}
}
public static void main(String args[]) {
SleepExample sleepThread = new SleepExample();
sleepThread.start();
}
}
146