First, ThreadLocal
With thread safety implemented using the WAIT/NOTIFY approach, performance will be greatly impacted. The solution is to use space for time and thread safety without locking.
To take a look at a small example, set in the thread, get is threadlocal
1 Public classconnthreadlocal {2 3 Public Staticthreadlocal<string> th =NewThreadlocal<string>();4 5 Public voidsetth (String value) {6 Th.set (value);7 }8 Public voidGetth () {9System.out.println (Thread.CurrentThread (). GetName () + ":" + This. Th.get ());Ten } One A Public Static voidMain (string[] args)throwsinterruptedexception { - - Finalconnthreadlocal ct =Newconnthreadlocal (); theThread T1 =NewThread (NewRunnable () { - @Override - Public voidrun () { -Ct.setth ("Zhang San"); + ct.getth (); - } +}, "T1"); A atThread t2 =NewThread (NewRunnable () { - @Override - Public voidrun () { - Try { -Thread.Sleep (1000); - ct.getth (); in}Catch(interruptedexception e) { - e.printstacktrace (); to } + } -}, "T2"); the * T1.start (); $ T2.start ();Panax Notoginseng } - the}
View Code
Second, single and multi-threaded
The Singleton has a hunger pattern and lazy mode, but these two modes are not available in multithreaded situations. Consideration of new and thread-safe issues in multi-threading generally consider two ways of double check instance and static inner class to implement singleton mode.
Static inner class mode:
1 Public classinnersingleton{2 Private Static classsingleton{3 Private StaticSingleton single =NewSingleton ();4 } 5 PublicSingleton getinstance () {6 returnSingleton.single; 7 }8}
View Code
Double check instance mode:
1 Public classDubblesingleton {2 3 Private StaticDubblesingleton ds;4 5 Public StaticDubblesingleton Getds () {6 if(ds = =NULL){7 Try {8 //simulate the preparation time for initializing objects ...9Thread.Sleep (3000);Ten}Catch(interruptedexception e) { One e.printstacktrace (); A } - synchronized(Dubblesingleton.class) { - if(ds = =NULL){ theDS =NewDubblesingleton (); - } - } - } + returnds; - } + A Public Static voidMain (string[] args) { atThread T1 =NewThread (NewRunnable () { - @Override - Public voidrun () { - System.out.println (Dubblesingleton.getds (). Hashcode ()); - } -}, "T1"); inThread t2 =NewThread (NewRunnable () { - @Override to Public voidrun () { + System.out.println (Dubblesingleton.getds (). Hashcode ()); - } the}, "T2"); *Thread t3 =NewThread (NewRunnable () { $ @OverridePanax Notoginseng Public voidrun () { - System.out.println (Dubblesingleton.getds (). Hashcode ()); the } +}, "T3"); A the T1.start (); + T2.start (); - T3.start (); $ } $ -}
View Code
Architects form--6. Single and multithreaded, ThreadLocal