🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The sleep method in Java is used to pause the execution of the current thread for a specified period of time. This method is part of the Thread class and allows you to temporarily suspend a thread's execution without terminating it. The sleep method can throw an InterruptedException, so it must be handled using a try-catch block.
Table of Contents
sleepMethod Variants- Example: Using
sleep(long millis)Method - Example: Using
sleep(long millis, int nanos)Method - Handling
InterruptedException - Conclusion
1. sleep Method Variants
sleep(long millis)
This method pauses the execution of the current thread for the specified number of milliseconds.
Syntax:
public static void sleep(long millis) throws InterruptedException
sleep(long millis, int nanos)
This method pauses the execution of the current thread for the specified number of milliseconds plus nanoseconds.
Syntax:
public static void sleep(long millis, int nanos) throws InterruptedException
2. Example: Using sleep(long millis) Method
Let's create an example to demonstrate how to use the sleep(long millis) method to pause the execution of a thread.
Example:
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the name of the thread
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running. Iteration: " + i);
try {
Thread.sleep(1000); // Sleep for 1000 milliseconds (1 second)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
thread1.start(); // Start thread1
thread2.start(); // Start thread2
}
}
Output:
Thread-1 is running. Iteration: 0
Thread-2 is running. Iteration: 0
Thread-1 is running. Iteration: 1
Thread-2 is running. Iteration: 1
Thread-1 is running. Iteration: 2
Thread-2 is running. Iteration: 2
Thread-1 is running. Iteration: 3
Thread-2 is running. Iteration: 3
Thread-1 is running. Iteration: 4
Thread-2 is running. Iteration: 4
Explanation:
- The
MyThreadclass extends theThreadclass and sets the name of the thread. - The
runmethod prints the name of the current thread and the iteration count, then sleeps for 1000 milliseconds (1 second). - In the
mainmethod, twoMyThreadobjects are created and started. - Each thread prints its name and iteration count, then sleeps for 1 second before continuing to the next iteration.
3. Example: Using sleep(long millis, int nanos) Method
This example demonstrates using the sleep(long millis, int nanos) method to pause the execution of a thread for a specified number of milliseconds plus nanoseconds.
Example:
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the name of the thread
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running. Iteration: " + i);
try {
Thread.sleep(1000, 500000); // Sleep for 1000 milliseconds plus 500,000 nanoseconds (0.5 milliseconds)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
thread1.start(); // Start thread1
thread2.start(); // Start thread2
}
}
Output:
Thread-1 is running. Iteration: 0
Thread-2 is running. Iteration: 0
Thread-1 is running. Iteration: 1
Thread-2 is running. Iteration: 1
Thread-1 is running. Iteration: 2
Thread-2 is running. Iteration: 2
Thread-1 is running. Iteration: 3
Thread-2 is running. Iteration: 3
Thread-1 is running. Iteration: 4
Thread-2 is running. Iteration: 4
Explanation:
- The
MyThreadclass extends theThreadclass and sets the name of the thread. - The
runmethod prints the name of the current thread and the iteration count, then sleeps for 1000 milliseconds plus 500,000 nanoseconds (0.5 milliseconds). - In the
mainmethod, twoMyThreadobjects are created and started. - Each thread prints its name and iteration count, then sleeps for 1.0005 seconds before continuing to the next iteration.
4. Handling InterruptedException
The sleep method throws an InterruptedException if the thread is interrupted while sleeping. This exception must be handled using a try-catch block.
Example:
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the name of the thread
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running. Iteration: " + i);
try {
Thread.sleep(1000); // Sleep for 1000 milliseconds (1 second)
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
return; // Exit the run method if interrupted
}
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
thread1.start(); // Start thread1
try {
Thread.sleep(3000); // Main thread sleeps for 3 seconds
thread1.interrupt(); // Interrupt thread1 after 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Thread-1 is running. Iteration: 0
Thread-1 is running. Iteration: 1
Thread-1 is running. Iteration: 2
Thread-1 was interrupted.
Explanation:
- The
MyThreadclass extends theThreadclass and sets the name of the thread. - The
runmethod prints the name of the current thread and the iteration count, then sleeps for 1000 milliseconds (1 second). - If the thread is interrupted while sleeping, the
InterruptedExceptionis caught, and a message is printed indicating that the thread was interrupted. Therunmethod then exits. - In the
mainmethod, aMyThreadobject is created and started. - The main thread sleeps for 3 seconds and then interrupts
thread1.
5. Conclusion
The sleep method in Java is used for controlling the execution flow of threads. By using the sleep(long millis) and sleep(long millis, int nanos) methods, you can pause a thread's execution for a specified amount of time. Handling InterruptedException is crucial when using the sleep method to ensure that your program can gracefully handle interruptions.
Happy coding!
Comments
Post a Comment
Leave Comment