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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With