The solution to question is quite simple, Thread behaviour is unpredictable because execution of Threads depends on Thread scheduler, thread scheduler may have different implementation on different platforms like windows, unix etc. Same threading program may produce different output in subsequent executions even on same platform.
To achieve we are going to create 2 threads on same Runnable Object, create for loop in run() method and start both threads. There is no surety that which threads will complete first, both threads will enter anonymously in for loop.
Let’s take a example>
class MyRunnable implements Runnable{
public void run(){
System.out.println("in run() method");
for(int i=0;i<5;i++){
System.out.println("i="+i+" ,ThreadName="+Thread.currentThread().getName());
}
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
public static void main(String...args){
System.out.println("In main() method");
MyRunnable runnable=new MyRunnable();
Thread thread1=new Thread(runnable);
Thread thread2=new Thread(runnable);
thread1.start();
thread2.start();
System.out.println("end main() method");
}
}
|
Let’s execute this program first time.
We got below output :
/*OUTPUT
In main() method
in run() method
in run() method
i=0 ,ThreadName=Thread-1
i=0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-1
i=1 ,ThreadName=Thread-0
i=2 ,ThreadName=Thread-1
end main() method
i=2 ,ThreadName=Thread-0
i=3 ,ThreadName=Thread-1
i=3 ,ThreadName=Thread-0
i=4 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-0
*/
But, in the second execution was totally different.
/*OUTPUT
In main() method
end main() method
in run() method
i=0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-0
in run() method
i=0 ,ThreadName=Thread-1
i=1 ,ThreadName=Thread-1
i=2 ,ThreadName=Thread-1
i=3 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-1
i=2 ,ThreadName=Thread-0
i=3 ,ThreadName=Thread-0
i=4 ,ThreadName=Thread-0
*/
We cannot stay assure which Thread will complete first, in one the case main thread ended before Thread1 and Thread2. while in other Thread-1 started in mid of main thread.
So, this shows Threads have unpredictable behaviour in Java.
RELATED LINKS>
Thread basics >