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
Packagethread2; Public classconnthreadlocal { Public Staticthreadlocal<string> th =NewThreadlocal<string>(); Public voidsetth (String value) {Th.set (value); } Public voidGetth () {System.out.println (Thread.CurrentThread (). GetName ()+ ":" + This. Th.get ()); } Public Static voidMain (string[] args)throwsinterruptedexception {Finalconnthreadlocal ct =Newconnthreadlocal (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {CT.SETTH ("ABC"); CT.GETTH (); } }, "T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); CT.GETTH (); } Catch(interruptedexception e) {e.printstacktrace (); } } }, "T2"); T1.start (); T2.start (); } }
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:
Package bhz.base.conn011; Public class singletion { privatestaticclass innersingletion { Privatestaticnew singletion (); } Public Static singletion getinstance () { return innersingletion.single; } }
Double check instance mode:
Packagethread2; Public classDubblesingleton {Private StaticDubblesingleton ds; Public StaticDubblesingleton Getds () {if(ds = =NULL){ synchronized(Dubblesingleton.class) { if(ds = =NULL) {DS=NewDubblesingleton (); } } } returnds; } Public Static voidMain (string[] args) {Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {System.out.println (Dubblesingleton.getds (). Hashcode ()); } },"T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {System.out.println (Dubblesingleton.getds (). Hashcode ()); } },"T2"); Thread T3=NewThread (NewRunnable () {@Override Public voidrun () {System.out.println (Dubblesingleton.getds (). Hashcode ()); } },"T3"); T1.start (); T2.start (); T3.start (); } }
View Code
Threading Learning--(vi) Single and multithreaded, ThreadLocal