package general; class SharedObject{ void SharedMethod(String arg){ System.out.print("["); System.out.print(arg); try{ Thread.sleep(1000); } catch(InterruptedException e){ System.out.println("Interrupted"+e); } System.out.println("]"); } } class Thread1 implements Runnable{ String arg; SharedObject obj1; Thread t; public Thread1(SharedObject obj1, String arg){ this.arg=arg; this.obj1=obj1; t=new Thread(this); t.start(); } public void run(){ synchronized(obj1){ obj1.SharedMethod(arg); } } } class SynchEx1 { public static void main(String [] args){ SharedObject obj1=new SharedObject(); Thread1 t1=new Thread1(obj1, "Hello! "); Thread1 t2=new Thread1(obj1, "I"); Thread1 t3=new Thread1(obj1, "am"); Thread1 t4=new Thread1(obj1, "here"); try{ t1.t.join(); t2.t.join(); t3.t.join(); t4.t.join(); }catch(Exception e){ System.out.println(" main Thread Interrupted"); } } }
// here my concern is, I created thread t1, t2, t3, t4 in this order and t1 gets executed first because Here I am using synchronized block but after t1 gets completed it should go for t2 then t3 and so on but it executes first t1 after that last one then second last and so on....
So Please do let me know is there anything I am missing here or it is the problem of OS??