roshan dhb
roshan dhb

Reputation: 63

Synchronization method

I tried to create a five threads, accordingly if one thread invokes the synchronized method on one object(objsyn in this case) then all other threads should wait till the thread finishes with the object. So the output should come from thread 1 to thread 5 in order. But the output is 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();
        }
        }

Upvotes: 0

Views: 102

Answers (1)

kosa
kosa

Reputation: 66677

Thread execution order is not guaranteed. Synchronization make sure only one thread executing that block of code at a point of time, it doesn't care whether it is first thread (or) second thread.

If you want really execute a particular logic in order, then you don't really need threading. Remember that when you start a thread, it will be separate thread from main thread. May be answers for this question help you.

Upvotes: 5

Related Questions