2

can anyone please tell me why the synchronised keyword is not working.

package Threading;

class NewThreadt extends Thread { 

  synchronized void dota(int a){
      System.out.println(a);
  }

  // This is the entry point for the second thread. 
  public void run() { 
    try { 
      for(int i = 5; i > 0; i--) { 

       dota(i) ;
        Thread.sleep(500); 
      } 
    } catch (InterruptedException e) { 
      System.out.println("Child interrupted."); 
    } 
    System.out.println("Exiting child thread."); 
    System.out.println(Thread.currentThread());    
  } 
} 

class abc { 
  public static void main(String args[]) { 
    NewThreadt t=new NewThreadt();
    NewThreadt q=new NewThreadt();
    t.start();
    q.start();  


    System.out.println("Main thread exiting."); 
  } 
}

Output I am getting on executing above program:

5
5
4
4
3
3
2
2
1
1

The output that I want:

5
4
3
2
1
5
4
3
2
1
3
  • Marking the dota() method as synchronized only ensures that each call to dota() blocks any other call to dota() on the same instance of NewThreadt. It doesn't remotely do what you seem to think it does.
    – khelwood
    Nov 5, 2015 at 16:05
  • Why are you using threads if you want fully consequentially? -_- Nov 5, 2015 at 16:07
  • Congratulations, and an upvote, on a question that contains a complete test program illustrating the question, a sample of its actual output, and a clear statement of the expected output. That combination is surprisingly rare. Nov 5, 2015 at 16:46

1 Answer 1

1

To get what you want you need two changes:

  1. Synchronize both threads on the same object. Currently, they are each synchronizing on their own this.
  2. Put the synchronization outside the loop in run, so that one thread does the whole loop before the other enters it.

Here is a modified version of your NewThreadt class:

class NewThreadt extends Thread {

  private static Object lock = new Object();

  void dota(int a) {
    System.out.println(a);
  }

  // This is the entry point for the second thread.
  public void run() {
    synchronized (lock) {
      try {
        for (int i = 5; i > 0; i--) {

          dota(i);
          Thread.sleep(500);
        }
      } catch (InterruptedException e) {
        System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
      System.out.println(Thread.currentThread());
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.