I need to know, how the execution of this program of mine takes place. I will place my understanding as far as going statement by statement:
The main method gets called and the objects are created. Once the start method of first object is called, it waits for the thread to run. When it runs, it invokes the run method which in turn starts the for loop. At the beginning of the loop i have set Thread.sleep which makes this thread to sleep for 5seconds. After that it again starts and prints along the complete loop. Same when other thread is called.
However the output is reverse and is like {1,1 then 2,2 then 3,3 then 4,4}. Can anyone make understand how this goes about?
package thread;
public class th implements Runnable {
public void run() {
for (int i = 1; i < 5; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
th t1 = new th();
th t2 = new th();
Thread t = new Thread(t1);
Thread tn = new Thread(t2);
t.start();
tn.start();
}
}