Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java Threads work

I'm a Java learner, trying to understand Threads.

I was expecting output from my program below, in the order

Thread started Run Method Bye

But I get output in the order

Bye Thread started Run Method

Here is my code:

public class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread("Thread started");
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Bye");
    }
}

class MyThread implements Runnable
{
    Thread t;
    String s= null;

    MyThread(String str)
    { 
      s=str;
    }

    public void run()
    {
      System.out.println(s);
      System.out.println("Run Method");
    }
}
like image 619
Spands Avatar asked Jan 09 '23 04:01

Spands


1 Answers

In a multithreaded code there's no guarantee which thread will run in what order. That's in the core of multithreading and not restricted to Java. You may get the order t1, t2, t3 one time, t3, t1, t2 on another etc.

In your case there are 2 threads. One is main thread and the other one is firstThread. It's not determined which will execute first.

like image 126
uylmz Avatar answered Jan 16 '23 04:01

uylmz