In the static block of the previous Java class , it is introduced to the following: static blocks of a class are executed when the class is loaded, executed earlier than the constructor, and executed only once.
However, in the following example, it is found that the JVM does not execute the rest of the static modules (Java is an explanatory language):
1 /**2 * A hungry man mode of single case mode3 * 4 * @authorAdministrator5 *6 */7 Public classsingletonstarving {8 Static {9System.out.println ("This is starving Singleton3");Ten } One A /* - * 1. Privatize the construction method and cannot create objects directly from the outside - */ the Privatesingletonstarving () { -System.out.println ("This is starving Singleton2"); - } - + Static { -System.out.println ("This is starving Singleton5"); + } A at /* - * 2. Declaring a unique instance of a class, using the private static adornment - */ - Private StaticSingletonstarving instance=Newsingletonstarving (); - - Static { inSystem.out.println ("This is starving Singleton4"); - } to + /* - * 3. Provide a method for obtaining an instance, using the public static modifier the */ * Public Staticsingletonstarving getinstance () { $ returninstance;Panax Notoginseng } - the Public voidprint () { +System.out.println ("This is starving Singleton"); A } the + Public Static voidMain (string[] args) { - for(inti = 0; I < 2; i++) { $ singletonstarving.getinstance (). print (); $ } - } -}
Output Result:
This is starving Singleton3 This is starving Singleton5 This is starving Singleton2 This is starving Singleton4 This is starving Singleton This is starving Singleton
Analytical:
First the program enters from the main method, executes to 45 lines of the first loop, starts loading the class, also means to start the static module, and then output the 9th and 20 rows of the PrintOut method, output 3 and 5, interpreted to 26 rows because the class has been loaded once, so the load class will not be executed, Instead, the constructor is executed, so output 2, continue down, continue with the third static module, output 4, then the class load is complete, execute the first getinstance () return instance, execute print (), The loop body then executes 45 rows again, the static module executes only once (does not repeat printing 2,3,4), the singleton mode will no longer execute the constructor (does not print 2), so the second run to 45 rows will only execute print ().
Static block of Java class two