Thread behavior 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.
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());
}
}
}
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");
}
}
|
In the above program we created two threads, now its on thread scheduler to pick a thread and start it we have no control in it.
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
*/
Each time we execute this program it produces different output because we didn't not use synchronize block here.
No comments:
Post a Comment