1

I have Main class with main method. I create two Threads What i noticed that code from main thread executes before created Threads. What i was expecting is to run it simultaneous. Why code from main method executes berofe code from Threads?

Main.class:

public class Main extends Thread {
public static void main(String[] args) {
    NewThread thread = new NewThread("Thread1");
    NewThread thread2 = new NewThread("Thread2");
    for (int i = 0; i <3 ; i++) {
        System.out.println("From main thread");
    }
    thread.start();
    thread2.start();       

} }

NewThread.class

public class NewThread extends Thread{

public NewThread(String name) {
    this.setName(name);
}
public void run() {
    int clientnumber = 1;
    while(clientnumber!= 3) {
        System.out.println("server sent data to client: " + getName());
        clientnumber++;
    }
}

}

Output:

From main thread
From main thread
From main thread
server sent data to client: Thread2
server sent data to client: Thread1
server sent data to client: Thread2
server sent data to client: Thread1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Nikolas Bozic
  • 1,071
  • 2
  • 13
  • 20
  • 6
    Because you call `start` on the threads after your print from the main thread? – UnholySheep Mar 11 '18 at 22:16
  • even if it is after still same execution – Nikolas Bozic Mar 11 '18 at 22:16
  • 3
    Note that **three prints** is just too less to see the effect. It takes some time until the threads are actually running and doing stuff. In the meantime the three prints probably are already executed. Increase to `1_000` and you will see mixed outputs, or add artificial delay using `Thread.sleep(1000)`. – Zabuzard Mar 11 '18 at 22:17
  • In Java, main() is itself ran by a thread named **main**, and threads are async, so you can't expect simultaneous results, neither same results all time. –  Mar 11 '18 at 22:23
  • but i get always same result first main thread, than other threads simultaneosly – Nikolas Bozic Mar 11 '18 at 22:24
  • As said, increase the delay. Context switching is super expensive and the scheduler uses different methods for determining them. It's not "*one line for thread A, then one line for thread B, ...*". Instead it's more like thousands of lines, or rather seconds of CPU time, not nanoseconds. – Zabuzard Mar 11 '18 at 22:47
  • Editing your question invalidates the answers – OneCricketeer Mar 11 '18 at 22:50

3 Answers3

3

Why code from main method executes before code from Threads?

Simply, because it can.

When you start() a thread, either the parent thread or the child thread may be scheduled to run next. Or they may both scheduled simultaneously. Or an entirely different thread may be scheduled.

The Java language and runtime system make no guarantees of thread scheduling order. Furthermore thread scheduling behavior is liable to be different for different execution platforms1; e.g. depending on how many cores you have.

(Why? Because, this is how native thread scheduling works on a typical OS. Java can't fight this and still use native threads. Using user-space threads and thread scheduling has serious performance issues. Sun abandoned that approach decades ago.)

What do you do to solve this?

  • Don't make assumptions about scheduling, and the order in which threads will execute.

  • If your application really needs one thread to run before the other, use one of the concurrency primitives or classes to achieve it ... explicitly. (But beware that by forcing one thread to run before another you are reducing the effective concurrency.)

In your example, the problem is basically that your expectations were incorrect. It is no longer a problem once you have adjusted your expectations.


1 - Behavior is likely to be repeatable on a given platform, especially in a small / simple example like yours. But then again, it could change if you ran your test while the system was under heavy load. Remember: No guarantees!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Execution of other threads starts with .start() method - you call this method after loop printing informations to the console in `main.

EDIT: These lines are printed before lines from new threads, because it is likely to be faster to print 3 lines to the console than perform loops in other threads and then print. After edit that you made to the question - to see how all three threads (including thread containing main()) are working in the same time and to see the difference in order of printed lines - I suggest you to try one of the following ways to see the difference:

  1. Try to perform time-consuming operation in main() after starting new threads and before printing to the console in main() (you can think of that operation on your own or try one of these listed in these answers, or
  2. Try to increase number of loops (maybe even to few thousands) with statements printing to the console in each thread - you'll see that all threads work in the same time, or
  3. Simply call Thread.sleep(1000) (or higher number as the argument - it's number of milliseconds that you want the current thread to sleep) in main() after starting new threads and before printing lines from the main().
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
1

NewThread thread has to be started before it will start executing. You are starting both threads only after main() has processed the loop. What you want is probably:

new NewThread("Thread1").start();
new NewThread("Thread2").start(); 
for (int i = 0; i <3 ; i++) {
    System.out.println("From main thread");
}

However it's up to JVM and OS to schedule the threads. You still might observer the main() executing first before NewThread gets a chance to run.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111