I comprehend the basics of Java from the book by Herbert Shildt I decided to reproduce the example from the book:

public class Test { public static void main(String args[]) { Callme target = new Callme(); Caller obj1 = new Caller(target, "Welcome"); Caller obj2 = new Caller(target, "to synchronized"); Caller obj3 = new Caller(target, "world!"); try { obj1.t.join(); obj2.t.join(); obj3.t.join(); } catch(InterruptedException e) { System.out.println("interrupted!"); } } } class Callme { void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Thread is interrupted!"); } System.out.println("]"); } } class Caller implements Runnable{ String msg; Callme target; Thread t; public Caller(Callme trg, String s) { target = trg; msg = s; t = new Thread(this); t.start(); } public void run() { synchronized(target) { target.call(msg); } } } 

Judging by the textbook, the conclusion should be as follows:

 [Welcome] [to synchronized] [world!] 

Instead, we get the following:

 [Welcome] [world!] [to synchronized] 

I apologize in advance for the possibly Nubian question, but I don’t see an error in the emphasis.

UPD:

Even if you put a delay between the creation of objects as follows:

  Callme target = new Callme(); Caller obj1 = new Caller(target, "Welcome"); Caller obj2 = new Caller(target, "to synchronized"); Thread.sleep(700); Caller obj3 = new Caller(target, "world!"); 

it still fails to achieve the desired effect. As for me it is so very strange.

    3 answers 3

    The meaning of the example is as follows. On each cart there are two printing operations. Synchronization ensures that the method performs both prints before another thread can print something of its own.

    Without synchronization there will be something like

     [Welcome[to synchronized[world!] ] ] 

    The order of execution of threads is not deterministic. The one who enters the critical section faster will print, the rest will wait for the end.

      That's right, the order here is not guaranteed. The scheduler can pause any of the threads until the synchronized block and give processor time to another thread, regardless of when it was created. Synchronization in this case provides only the execution of the call method as a single thread at a time.

        I think the book does not say what should be strictly in this order.

        The order of execution of threads is not guaranteed, these three phrases can be displayed in any order.

        • The fact that the threads are executed in turn and there is a sense. Here, the Thread.sleep () method is used for clarity. Especially when creating obj1 ... 3 objects, the Caller () constructor is called in turn for each object. - Vlad Calca 1:01 pm
        • @VladKalco see Yura Ivanov's answer, understand why synchronized - Russtam