Why are the threads executed in this order?
java, multithreading
Solution
There really is no guaranteed order of execution when executing multiple threads. The threads are independent of each other.
The link in the source code explains it:
Here you can see that both outputs are different though our program code is same. It happens in thread program because they are running concurrently on their own. Threads are running independently of one another and each executes whenever it has a chance.
Problem
Practicing multi thread java examples ,here i am creating thread A in class A and thread B in class B .Now starting those two threads by creating objects .here i am placing the code ``` package com.sri.thread; class A extends Thread { public void run() { System.out.println("Thread A"); for(int i=1;i<=5;i++) { System.out.println("From thread A i = " + i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { System.out.println("Thread B"); for(int i=1;i<=5;i++) { System.out.println("From thread B i = " + i); } System.out.println("Exit from B"); } } public class Thread_Class { public static void main(String[] args) { new A().start(); //creating A class thread object and calling run method new B().start(); //creating B class thread object and calling run method System.out.println("End of main thread"); } //- See more at: http://www.java2all.com/1/1/17/95/Technology/CORE-JAVA/Multithreading/Creating-Thread#sthash.mKjq1tCb.dpuf } ``` i didn't understand the flow of execution ,tried by debugging but didn't get it.how the flow of execution is .Here i am placing the out put which confusing me. ``` Thread A Thread B End of main thread From thread B i = 1 From thread B i = 2 From thread B i = 3 From thread B i = 4 From thread B i = 5 Exit from B From thread A i = 1 From thread A i = 2 From thread A i = 3 From thread A i = 4 From thread A i = 5 Exit from A ``` Why does the loop in thread B finish before the loop in thread A is entered?