I was trying to test/learn a few basic things in threading(Java) and came across a simple but confusing output. Following are my classes
public class CopyMaster implements Runnable{
@Override
public void run() {
System.out.println("Run called from Copy Master for thread "+Thread.currentThread().getName());
}
}
Main Class from where I am invoking threads
public class Main {
public static void main(String[] args) {
Thread[] threadArray = new Thread[4];
for(int i=0; i<threadArray.length; i++){
threadArray[i] = new Thread(new CopyMaster());
}
for(Thread t : threadArray){
//[Line of intrest]System.out.println("Starting Thread "+t.getName());
t.start();
}
}
}
OP(With Line of Interest un-commented)
Starting Thread Thread-0
Starting Thread Thread-1
Run called from Copy Master for thread Thread-0
Starting Thread Thread-2
Run called from Copy Master for thread Thread-1
Starting Thread Thread-3
Run called from Copy Master for thread Thread-2
Run called from Copy Master for thread Thread-3
OP(With Line of Interest commented)
Run called from Copy Master for thread Thread-2
Run called from Copy Master for thread Thread-3
Run called from Copy Master for thread Thread-0
Run called from Copy Master for thread Thread-1
I have tried running the code multiple times and observed that the sequence of print-outs are random in commented line of interest and in un-commented one its proper(in sequence)...
Why is it behaving like that?//EDITED as this confuses what i want to mean
EDIT:
I understand that threads behaves unpredictably but my main question is why it maintains oredr ALWAYS in one case and why random behavior is there in other case?