java - Synchronization method -
i tried create 5 threads, accordingly if 1 thread invokes synchronized method on 1 object(objsyn in case) other threads should wait till thread finishes object. output should come thread 1 thread 5 in order. output coming out of order.
class synctest extends thread { public synchronized void display() { try{thread.sleep(5000*((long)(math.random())));} catch(exception e){} system.out.println("from synchornized thread "+ thread.currentthread().getname()); } public synchronized void run() { synctest objsyn = new synctest(); objsyn.display(); } public static void main(string args[]) { synctest objsy = new synctest(); thread t1 = new thread(objsy,"thread 1"); thread t2 = new thread(objsy,"thread 2"); thread t3 = new thread(objsy,"thread 3"); thread t4 = new thread(objsy,"thread 4"); thread t5 = new thread(objsy,"thread 5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
thread execution order not guaranteed. synchronization make sure 1 thread executing block of code @ point of time, doesn't care whether first thread (or) second thread.
if want execute particular logic in order, don't need threading. remember when start thread, separate thread main thread. may answers question you.
Comments
Post a Comment