i have created a JAVA prog to check the working of synchronized block . But it is giving random answers every time. Can anyone explain why it is behaving like that.
Program:
public class ThreadSyncex1 extends Thread {
public static void main(String[] args) {
call a=new call();
call b=new call();
a.start();
b.start();
try {
a.join();
b.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class call extends Thread {
public void run() {
System.out.println(System.currentTimeMillis());
synchronized(this)
{
try {
System.out.println(Thread.currentThread().getName());
System.out.println("Success...");
Thread.sleep(500);
} catch(Exception e){
System.out.println(e);
}
}
}
}
It is giving output :
1502683588129
1502683588129
Thread-1
Thread-0
Success...
Success...
and
1502683592249
1502683592249
Thread-1
Success...
Thread-0
Success...