3

Hy, i try to follow this http://www.studytonight.com/java/synchronization.php

here's my code

class First {
     public void display(String msg)   
     {
         System.out.print("["+msg);
         try {
             Thread.sleep(1000);
         } catch (InterruptedException ex) {}
         System.out.println("]");
     }
}

class Second extends Thread{
    String msg;
    First fobj;

    Second(First fp,String str){
        msg=str;
        fobj=fp;
        start();
    }

    public void run(){
        synchronized(fobj){
            fobj.display(msg);
        }
    } 
}

public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
        First f=new First();
        Second s1=new Second(f,"welcome");
        Second s2=new Second(f,"new");
        Second s3=new Second(f,"programmer");
    }

}

and here's my result

run:
[welcome]
[programmer]
[new]
BUILD SUCCESSFUL (total time: 3 seconds)

what's wrong with my code? why the result isn't welcome new programmer ?

1 Answer 1

3

All the threads start almost at the same time, and compete with each other to get the lock on the shared object.

There is no guarantee that the second thread asks for the lock before the third one. And even if that is the case, the lock is not fair, so there is no guarantee that the first thread waiting for the lock will get it first.

The only guarantee you can have with the above code is that only one of the thread will be able to execute the synchronized method at a time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.