views:

111

answers:

1

Given this code:

public class Messager implements Runnable {            

  public static void main(String[] args) {   
      new Thread(new Messager("Wallace")).start();    
      new Thread(new Messager("Gromit")).start();             
  }             
  private String name;                 
  public Messager(String name) { this.name = name; }             
  public void run() {    
      message(1); message(2);    
  }           
  private synchronized void message(int n) {    
    System.out.print(name + "-" + n + " ");    
  }    
}

I understand that the synchronized keyword makes the thread dependent on the object's lock. Questions:

a) Is the lock released as soon as the method marked as synchronized finishes? Or as soon as the thread's run() method finishes b) Can I ensure that any one of the threads will print its name and 1 2 before the other?

+2  A: 

A. Yes. It's released as soon as the synchronized function finishes.
B. Yes. You can, but if you wanted to do so, why would you write multithreaded code in the first place? synchronized guarantees atomicity, not anything regarding the order, but you can enforce order by waiting for a flag to change. Anyway, what you are trying to enforce is sequentiality. You get this for free in single-threaded environments :)

Mehrdad Afshari
Oh, I'm just asking a "what if" question. I'm studying for the scjp. Thanks.
omgzor
dmindreader, please add new tag scjp to future scjp questions, thanks.
Thorbjørn Ravn Andersen