Sumit Singh
Sumit Singh

Reputation: 1115

How threads are executed in the memory in Java?

I am learning about Thread in Java. I was trying to fetch which thread is running. But, I am not able to understand the order of the output.

Following is my code

public class practice extends Thread {

public void run(){  
      for(int i=1;i<4;i++){  
         
        System.out.println(i); 
        System.out.println(Thread.currentThread().getName()); 
      }  
     
     }  

public static void main(String[] args) {
    
    practice t1=new practice();  
      practice t2=new practice();  
      practice t3=new practice();  
      
      t1.start();  
      t2.start(); 
      t3.start(); 
    }

}

Output:

1
1
1
Thread-1
2
Thread-1
3
Thread-1
Thread-0
2
Thread-0
3
Thread-0
Thread-2
2
Thread-2
3
Thread-2

Can anyone help me out in understand the order of output. Thanks in advance.

Upvotes: 2

Views: 585

Answers (2)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11120

Threads, by their nature, are concurrent to each other. This means, that two (or more) threads compete for the same resource (CPU) when they are executed at the same time, and CPU switches itself from executing one to another in a random-to-you (unpredictable) order. You can't and won't know to which execution path (Thread) your CPU and OS architecture will decide to jump. Moreover, in some languages, this may be a question of the OS architecture, in some - the question of CPU architecture only, and in some - question of both. It depends on how that language's architecture manages threads.

Note, that even if two threads are parallel - i.e. they execute in parallel on two different cores - you still are unable to predict which core will execute instruction first.

Because of the points above, you may be getting a different order of execution of your code, each time you run it.

Upvotes: 5

JovoH
JovoH

Reputation: 148

First .. please format your code for better visibility.Then use java naming convention.To find them out look here. It seems that you are a beginner in Threads and not understanding them in the first glance is completely OK.The unexpected order is related to OS scheduling and the concept of executing instructions and not methods concurrently, this mean that concurrent execution does not mean that run method will run concurrently, that means that everything (every instruction) in that method can/will run concurrently. Just keep learning Threads are (maybe) the most difficult area of Java but also the most interesting.

Upvotes: 1

Related Questions