0

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...
ivan.sim
  • 8,972
  • 8
  • 47
  • 63
Akshaya KAushik
  • 31
  • 1
  • 12
  • 3
    Your threads are effectively unsynchronized because they're synchronizing on themselves. Even if they did share a common monitor, there's no guarantee which thread would obtain it first. – shmosel Aug 14 '17 at 04:18
  • 2
    Why tag java 8 is relevant? – Ori Marko Aug 14 '17 at 04:20
  • try to put synchronized(this) before you call the methods – gever Aug 14 '17 at 04:31
  • 1
    or do synchronized(a) and call a.start() and the same for b – gever Aug 14 '17 at 04:32
  • https://stackoverflow.com/questions/2056243/java-synchronized-block-for-class – Viet Aug 14 '17 at 04:33
  • 1
    @shmosel - Thanks for reply. I got it I was not actually making run method synchronized. Instead I need to access a shared resource inside run method and make it synchronized – Akshaya KAushik Aug 14 '17 at 05:09

0 Answers0