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 keyword synchronizedmakes the thread dependent on locking the object. Questions:

a) Is the lock closed as soon as the method marked as synchronizedends? Or, as soon as the thread method run()ends b) Can I guarantee that any of the threads will print its name 1 2before the other?

+3
source share
1 answer

. . , synchronized.
B. . , , ? synchronized , - , , . , , , - . :)

+2

Source: https://habr.com/ru/post/1725555/


All Articles