hi sanjeev,
//code number 1
class MyThread extends Thread{
public MyThread(
String name){
super(name);
}
public synchronized void run(){
for(int i = 0 ; i<50 ;i++)
System.out.println(Thread.currentThread().getName());
try{Thread.sleep(10);}catch(Exception e){}
}
public static void main(String [] args){
new MyThread ("one").start();//Thread number one
new MyThread ("two").start(); //Thread number two
new MyThread ("three").start(); //Thread number three
}
}
//code number 2
class MyThread implements Runnable{
public synchronized void run(){
for(int i = 0 ; i<50 ;i++)
System.out.println(Thread.currentThread().getName());
try{Thread.sleep(10);}catch(Exception e){}
}
public static void main(String [] args){
MyThread td = new MyThread();
Thread t1 = new Thread(td ,"One" );
Thread t2 = new Thread(td ,"two" );
Thread t3 = new Thread(td ,"three" );
t1.start();
t2.start();
t3.start();
}
}
Once a Thread acquires lock of an object (by entering synchronized method of that object) no other Thread can call any synchronized method of that class on that object .
in code number 1 three Thread objects are created and hence they access run() method randomly even if it’s synchronized . reason being these are three different Threads.
in code number 2 three Thread objects are created and given the the same Runnable but as method run() is synchronized once a Thread acquires lock no other Thread can call any synchronized method of that class on that object so second hread will enter to run() method only if first Thread entered to run() leves the lock acquired.
Serial execution of statements here not guaretees any execution ordered.it is random all the time.JVM may choose any of the Thread to be currently running Thread at any time until unless priorities are not given and JVM also supports priorities.
It wil be more clear you please compile and run the codes that I written.
If still any confusion please let me know..
Regards