Reputation: 95
I'm a bit confused about how Thread.sleep() works:
If i call it inside the main method, and there are other created threads that are running. What would it pause: The main thread alone or all its subThreads along with it (considering them as a part of the main thread)? For example:
public static void main(String arg[])
{
Thread t1 = new Thread();
t1.start();
Thread.Sleep(1000);
}
If I invoke the sleep()
method inside the run()
method of a thread, when calling the start()
method for the thread inside main, does it pause other threads, too? Because that happened with me ... although I know that in this case it should only pause the thread it was called inside
For example:
//thread Tester has a sleep() in its run() while NoSleep doesn't have
public static void main(String arg[])
{
Tester t1 = new Tester();
NoSleep t2 = new NoSleep();
t1.start();
t2.start();
}
In a code like this, both t2
and t1
pause I don't understand why.
Upvotes: 1
Views: 2808
Reputation: 338795
In Java, threads are all equal peers, without grouping, parenting, or ownership.
So sleeping any one thread has no direct effect on other threads.
Calling Thread.sleep
sleeps whatever thread executes that method. Utterly simple, nothing more to explain.
As the Thread.sleep
Javadoc says:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
By the way, in modern Java we rarely need to address the Thread
class directly. Instead we use executor service(s) to run Runnable
or Callable
tasks. So no need to call new Thread
. And no need to extend from Thread
.
Tip: In recent versions of Java, we can pass a Duration
object to the sleep
method rather than a count of milliseconds.
Thread.sleep( Duration.ofSeconds( 42 ) ) ;
Upvotes: 4
Reputation: 11
I know I'm late to the party but to answer your question explicitly - Thread.sleep(n)
where n is in milliseconds causes current thread to sleep and doesn't affect the other threads.
Thread.sleep(1000)
inside main method, like below, your main thread will sleep for 1 seconds while other threads will continue to run.class Task extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(
"Hello! I am " + Thread.currentThread().getName() + " running without sleep - " + i);
}
}
}
public class ThreadSleepExample {
public static void main(String[] args) throws InterruptedException {
Task task = new Task();
task.start();
task.setName("Task Thread");
Thread.sleep(1000);
Thread.currentThread().setName("Main Thread");
System.out.println(
"Hello! I am " + Thread.currentThread().getName() + " and I slept for a while"); //This line gets printed after 1 second.
}
}
Output -
Hello! I am Task Thread running without sleep - 0
Hello! I am Task Thread running without sleep - 1
Hello! I am Task Thread running without sleep - 2
Hello! I am Main Thread and I slept for a while
Thread.sleep(n)
within a run method, it causes that thread to sleep and other threads including the main thread remains unaffected.class TaskWithSleep extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(
"Hello! I am " + Thread.currentThread().getName() + " running with sleep - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class TaskWithoutSleep extends Thread {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(
"Hello! I am " + Thread.currentThread().getName() + " running without sleep - " + i);
}
}
}
public class ThreadSleepExample {
public static void main(String[] args) {
TaskWithSleep sleepTask = new TaskWithSleep();
sleepTask.setName("SleepTask Thread");
TaskWithoutSleep withoutSleepTask = new TaskWithoutSleep();
withoutSleepTask.setName("WithoutSleepTask Thread");
sleepTask.start();
withoutSleepTask.start();
Thread.currentThread().setName("Main Thread");
System.out.println("I am " + Thread.currentThread().getName()
+ " and I remain unaffected by sleep inside other threads");
}
}
Here, SleepTask Thread
will pause for 1 second after printing each line. Whereas other threads like WithoutSleepTask Thread
and Main Thread
will continue to execute.
Here is the output -
I am Main Thread and I remain unaffected by sleep inside other threads
Hello! I am WithoutSleepTask Thread running without sleep - 0
Hello! I am SleepTask Thread running with sleep - 0
Hello! I am WithoutSleepTask Thread running without sleep - 1
Hello! I am WithoutSleepTask Thread running without sleep - 2
Hello! I am SleepTask Thread running with sleep - 1
Hello! I am SleepTask Thread running with sleep - 2
So in your case t1
should sleep and t2
should execute normally.
Upvotes: 0
Reputation: 27125
Thread.sleep()
is one of a number of things in Java that have really awful names.* Don't think of it "sleeping" any thread. There's a much simpler way to think about it:
Thread.sleep(n)
does NOTHING.
It does nothing for at least n
milliseconds, and then it returns. That is all you need to know about sleep()
(at least, it's all you need to know until you become a maintainer of a Java Runtime Environment.)
* Java was invented by several really smart, PhD. computer scientists. Java is a simple, beautiful language; but they bestowed names on certain things that maybe seem obvious to experts, but which sometimes can be really confusing to beginners.
Upvotes: 0
Reputation: 4620
Thread.sleep() pauses the current thread inside which the code is being executed, It have no impact on other threads. That thread can be 'main' thread or threads spawned (started) from main thread.
However Thread.sleep() is not the way to go to implement asynchronous tasks, like suspending some thread to wait by Thread.sleep() and then guessing that after that much time I can resume my thread and hoping that the event must have been completed for which your sleeping thread was waiting for. You will some low level mechanism like notify, wait, notifyAll . Rather use Semaphores, Countdown latch and other better wrappers as suggested in the other answer. Comment below for more information or doubts you have, happy to help
Upvotes: 0