public static void main(Sting args[]){ Object a=null; new Thread(){ a=new xxx() }.start(); new Thread(){ a=new xxx() }.start(); }
I would like to ask, there is complex object initialization logic in the xxx() method. Is the object created by the new keyword atomic? If not, will there be a problem of object initialization disorder?
I don’t understand what you mean, if my guess is correct:
It all depends on the specific logic in your construction method. After all, the code is written by humans.
Output:
Another example, the constructor contains a synchronization block, and each thread needs to wait for the execution of the previous thread to complete before it can execute.
Output:
It is recommended to refer to the thread-safe singleton mode
No, for example, if multiple pieces of logic are written in the construction method, it can be interrupted when the construction method is executed.
The description of "atomicity" is too abstract. When the poster asks questions, it is best not to think that everyone has exactly the same understanding of a certain word. All I can say is that the constructor is thread-safe. For each object, the constructor will only be executed once and by one thread.