First write a singleton, lazy mode:
Public class Singledemo { privatestaticnull; Private Singledemo () {} Public Static Singledemo getinstance () { ifnull) { new Singledemo (); } return s; }}
Write a test class:
Public class ThreadDemo3 { publicstaticvoid main (string[] args) { = Singledemo.getinstance (); = singledemo.getinstance (); = = s2);} }
The running result is always true, stating that there is no problem with a single thread, and the following is a multi-thread access to the singleton
Public class Implements Runnable { // Store Singleton object, use set to not hold duplicate element public new hashset< Singledemo>(); @Override publicvoid run () { // get a singleton Singledemo s = singledemo.getinstance (); // Add a single case Singles.add (s); }}
Using multiple threads for concurrent access to a single example:
Public classThreadDemo3 { Public Static voidMain (string[] args) {//Singledemo S1 = singledemo.getinstance ();//Singledemo s2 = singledemo.getinstance ();//System.out.println (s2 = = s2);ThreadTest T =Newthreadtest (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); NewThread (t). Start (); System.out.println (T.singles); }}
The results of the operation are as follows:
[[Email protected], [email protected]]
Or
[[email protected]]
Describes thread concurrency access security issues, not all of which are the same instance
How to solve the thread safety problem?
Of course, the sync lock mechanism is used.
The following improvements to the single example:
Public class Singledemo { privatestaticnull; Private Singledemo () {} Public Static synchronized Singledemo getinstance () { ifnull) { new Singledemo (); } return s; }}
Thread safety resolves after adding a sync function
Run multiple times to get the same instance without 2 instances
[[email protected]]
However, in the case of multi-threaded concurrent access, each thread to obtain an instance to determine the lock, efficiency is low, in order to improve efficiency, I added a double-judge method, solve the problem of efficiency
The code is as follows;
Public classSingledemo {Private StaticSingledemo s =NULL; PrivateSingledemo () {} Public StaticSingledemo getinstance () {/*if the first thread obtains an instance object of the singleton, the subsequent thread does not need to enter the synchronization code block when it acquires the instance .*/ if(s = =NULL){ //the lock used for synchronizing code blocks is a singleton bytecode file object and can only be used with this lock synchronized(Singledemo.class){ if(s = =NULL) {s=NewSingledemo (); } } } returns; }}
In this way to solve the lazy-type thread safety problems, but also improve efficiency, but in the actual development or use a hungry man-style comparison, after all, this code is more, more cumbersome.
Java design pattern--to solve the lazy thread safety problem in the single-case design pattern