简体   繁体   中英

Understanding synchronized

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM