I can not understand why the messages are not displayed in the order in which they were created, that is, obj1, obj2, obj3 in main are created one after the other and initialized "1", "2", "3", respectively, but when started, it is not "1 , 2,3 ", and" 1,3,2 ", and if you create objects in the order of obj1, obj3, obj2, then everything is displayed as it should, that is," 1,2,3 ". How many I don’t look at the code, but I don’t see a problem (or don’t know what to look for, as I just started to learn multithreading).
public class Main { public static void main(String[] args) { Callme target = new Callme(); Caller obj1 = new Caller(target, "1"); Caller obj2 = new Caller(target, "2"); Caller obj3 = new Caller(target, "3"); try { obj1.t.join(); obj2.t.join(); obj3.t.join(); } catch (InterruptedException e) { System.out.println("Прервано"); } } } class Callme { synchronized void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Прерван"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } @Override public void run() { target.call(msg); } }