Why are threads running in this order?

Practicing a few examples of java threads, here I create thread A in class A and thread B in class B. Now start these two threads by creating objects. Here I post 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 did not understand the flow of execution, tried debugging, but did not receive it. Like a thread of execution. This is how I put out what bothers 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 end before entering the loop in thread A?

+4
source share
3 answers

In fact, there is no guaranteed execution order when executing multiple threads. The threads are independent of each other.

The link in the source code explains this:

Here you can see that both outputs are different from each other, although our program code is the same. This happens in the thread program because they work simultaneously on their own. Threads work independently of one another, and each is executed every time he has a chance.

+4
source

If you have multiple processors, threads share the processor in the timeline. The total execution time of one of your threads may be less than a time slice, so no matter what thread is sent, it will be completed first before everything is started.

Try adding a short call to Thread.sleep in the startup methods.

+5
source

Threads are performed simultaneously. One of them is not executed inside the other. Each thread receives processor time, does some work, and then waits while the processors are busy with other things. It may work differently each time depending on what else is happening on the computer.

If you expected the output messages of the streams to be interlaced, they will, to some extent, increase your loops to several thousand iterations. Right now, the code ends so fast that it’s hard to see that they really work in parallel.

+1
source

Source: https://habr.com/ru/post/1496320/


All Articles