Class 7: Pausing a Thread with sleep()
Learn how to temporarily pause a thread using Java's sleep() method.
1. Welcome to Part 2 — Working with Threads!
Congratulations on completing Part 1 of our Java Multithreading course!
So far, we have learned how to create threads, assign tasks to them, identify them, and understand their lifecycle.
Now we will learn how to work with threads while they are executing.
Let's begin with a simple question:
Can we temporarily pause a thread while it is doing its work?
Yes! Java provides a method called sleep() for this purpose.
2. What Does sleep() Do?
Imagine that you are performing a task and decide to take a short break before continuing.
You stop working for a few seconds and then continue from where you left off.
A similar thing can happen with a Java thread.
The sleep() method temporarily pauses the execution
of the current thread for a specified amount of time.
For example, if we ask a thread to sleep for two seconds, it pauses for approximately two seconds before becoming eligible to continue.
We use the following method:
Thread.sleep(2000);
Here, 2000 represents 2000 milliseconds,
which is equal to two seconds.
Remember:
- 1000 milliseconds = 1 second
- 2000 milliseconds = 2 seconds
- 5000 milliseconds = 5 seconds
3. Our First Example Using sleep()
Let's write a simple Java program where a thread prints a message, pauses for two seconds, and then prints another message.
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
System.out.println("Thread resumed");
});
thread.start();
}
}
Possible output:
Thread started
(wait for approximately 2 seconds)
Thread resumed
Let's understand what happens step by step:
- We create a new thread.
- We start the thread using
start(). - The thread prints "Thread started".
- It calls
Thread.sleep(2000). - The thread pauses for approximately two seconds.
- After the pause, it continues and prints "Thread resumed".
Notice that the thread does not start from the beginning after sleeping. It continues from the next line of code.
4. Why Do We Need try-catch with sleep()?
You may have noticed something new in our example:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
Why do we need this?
The sleep() method can be interrupted while the thread
is sleeping.
Java represents this situation using an exception called
InterruptedException.
Because this is a checked exception, Java requires us to handle it
using try-catch or declare it using throws.
For now, remember that whenever we use Thread.sleep(),
we must handle this exception.
We will understand thread interruption properly in Class 9.
5. Pausing the Main Thread
So far, we have used sleep() inside a newly created thread.
But what happens if we use it directly inside the main() method?
Remember, the main() method is executed by the main thread.
Therefore, calling Thread.sleep() inside main()
pauses the main thread.
Let's look at an example:
public class Main {
public static void main(String[] args) {
System.out.println("First message");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("Main thread was interrupted");
}
System.out.println("Second message");
}
}
Output:
First message
(wait for approximately 3 seconds)
Second message
The main thread pauses for approximately three seconds between printing the two messages.
This is an important point:
Thread.sleep() pauses the thread that calls it, not every thread in the application.
6. Does sleep() Stop Other Threads?
No. This is one of the most important things to understand about
sleep().
Suppose we have two threads:
- Thread 1 prints a message and sleeps for two seconds.
- Thread 2 keeps printing its own messages.
When Thread 1 sleeps, Thread 2 can continue executing.
Let's see this in code:
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread 1 interrupted");
}
System.out.println("Thread 1 finished");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 is working");
});
thread1.start();
thread2.start();
}
}
One possible output is:
Thread 1 started
Thread 2 is working
Thread 1 finished
The exact order can vary, but Thread 1's sleep does not force Thread 2 to pause.
Each thread has its own execution.
7. Important Things to Remember About sleep()
Thread.sleep()pauses the currently executing thread.- The time is specified in milliseconds.
- 1000 milliseconds is equal to one second.
- The thread enters the TIMED_WAITING state while sleeping.
- Sleeping does not terminate a thread.
- Other threads can continue executing while one thread sleeps.
- Sleeping does not release locks that the thread already holds.
- The pause is for at least the requested duration, but the thread may resume later depending on scheduling.
One more important point: sleep() is a static method
of the Thread class. We normally call it using
Thread.sleep().
8. Try It Yourself
Let's practise what we have learned.
Create a Java program that:
- Creates a new thread.
- Prints "Starting work".
- Pauses for three seconds using
Thread.sleep(). - Prints "Work completed".
Next, create another thread that prints a message while the first thread is sleeping.
Observe how one thread can sleep while another thread continues its work.
9. Test Your Understanding
Answer these five questions to check what you have learned.
Question 1: What does Thread.sleep(2000) do?
Question 2: Which thread is paused when Thread.sleep() is called?
Question 3: Which exception must we handle when using Thread.sleep()?
Question 4: What happens to another thread when one thread calls sleep()?
Question 5: Which thread state does a sleeping thread enter?
10. Class Summary
Let's revise what we learned today:
Thread.sleep()temporarily pauses the current thread.- The duration is specified in milliseconds.
- 1000 milliseconds equals one second.
- We must handle
InterruptedException. - Other threads can continue executing while one thread sleeps.
- A sleeping thread enters the TIMED_WAITING state.
Remember, sleep() is useful when we want a thread to pause temporarily before continuing its work.
Coming Up Next: Class 8
In our next class, we will learn about the join() method.
Imagine that one thread needs to wait until another thread finishes its work. How can we make that happen?
That's exactly what we will explore in the next class.
Your Course Progress
0% Completed
You have completed 7 out of 44 classes.