This question and explanation make total sense to me. I have a question about Threads that call the sleep method, and an example to help me explain.
class ThreadTest {
public static void main(String []args) throws InterruptedException {
Thread t1 = new Thread() {
public void run() { System.out.print("t1 "); }
};
Thread t2 = new Thread() {
public void run() { System.out.print("t2 "); }
};
t1.start();
t1.sleep(5000);
t2.start();
t2.sleep(5000);
System.out.println("main ");
}
}
So in this example, there are 3 threads, t1, t2, and main. And you are unable to say which thread gets executed when. But if you have calls to sleep, does that guarantee the order? Can you say for sure that it will print out t1, t2, and main in that order because of the calls to sleep?
Threads and Sleep
Moderator: admin
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Threads and Sleep
Practically, yes, it is almost a certainty that it will print t1, t2, and main. But technically, there is no 100% guarantee. The reason is this - A JVM implementation is under no obligation to behave in a particular way if that way is not required by the specification. So it is possible to write a compliant JVM that doesn't schedule thread t1 or t2 for some reason even if there is no thread running at that time. So it is still theoretically possible for main to be printed first. Even after the calls to sleep as shown in your code.
HTH,
Paul.
PS. Please include the question id in the subject of the topic so that other readers can see this discussion when they search for see the question.
HTH,
Paul.
PS. Please include the question id in the subject of the topic so that other readers can see this discussion when they search for see the question.
Who is online
Users browsing this forum: No registered users and 2 guests