Threads and Sleep
Posted: Tue Nov 29, 2016 2:21 pm
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?
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?