How Java Threads Works

I participate in Java, trying to understand the topics.

I was expecting output from my program below in order

Started Run Method Bye

But I get the output in order

Bye Thread Launches Launch 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");
    }
}
+4
source share
6 answers

In multi-threaded code, there is no guarantee which thread will work in which order. This is at the heart of multithreading and is not limited to Java. You can get the order t1, t2, t3 once, t3, t1, t2 on the other, etc.

In your case there are 2 threads. One of them is the main stream, and the other is the first. He did not determine what would be executed first.

+4
source

Threads - ( , -, ).

Thread.start() Thread, ( , , , ) java-. , firstThread.start() ( ).

(, zeroThread)

public static void main(String[] args)

, , Thread.sleep().

firstThread.start();

, , , firstThread. , , : :

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

join(), firstThread ( ), , ( , System.out.println( " " );.)

+3

, (, , ) , main() , . ExecutorService - .

import java.util.concurrent.*;                                                   

class MyThread implements Runnable { // ... }                                    

class MyProgram {                                                                
  public static void main(String[] args)                                         
  {                                                                              
    MyThread t1 = new MyThread();                                            
    MyThread t2 = new MyThread();                                            
    MyThread t3 = new MyThread();                                            

    // At this point, 3 threads teed up but not running yet                  

    ExecutorService es = Executors.newCachedThreadPool();                    

    es.execute(t1);                                                          
    es.execute(t2);                                                          
    es.execute(t3);                                                          

    // All three threads now running async                                   

    // Allow all threads to run to completion ("orderly shutdown")            
    es.shutdown();                                                           

    // Wait for them all to end, up to 60 minutes.  If they do not 
    // finish before then, the function will unblock and return false:          
    boolean finshed = es.awaitTermination(60, TimeUnit.MINUTES);             

    System.out.println("Bye");                                               
  }                                                                            
}                                                                               
+2

, Java- . , "" .

, , :

class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread();
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Thread Main");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread Main i = " + i);
        }
        System.out.println("Exit from Main");
    }
}

class MyThread implements Runnable
{
    public void run()
    {
        System.out.println("Thread MyThread");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread MyThread i = " + i);
        }
        System.out.println("Exit from MyThread");
    }
}
0

. , .

API.

, println() "bye", , Thread.start() . Thread.start() . run().

, "println" "thread.start()", println .

As a side element, and in general, you can try to use ExecutorService and Callable when you can, since this is a higher level, newer APIs.

0
source

When you start Thread, it will run in parallel with the current one, so there is no guarantee of the execution order.

Try something line by line:

public class RunnableThread {
    static 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");
        }
    }
    public static void main(String[] args) {
        MyThread t1= new MyThread("Thread started");
        Thread firstThread= new Thread(t1);
        firstThread.start();
        boolean joined = false;
        while (!joined)
            try {
                firstThread.join();
                joined = true;
            } catch (InterruptedException e) {}
        System.out.println("Bye");
    }
}
0
source

All Articles