As can be seen from the name of Threadlocal, this is a thread-local variable, that is, only when the front-thread can access, since it is only when the front-thread can access the data, is naturally thread-safe.
Public classThreadlocaldemo {Private Staticthreadlocal<simpledateformat> T1 =NewThreadlocal<>(); Public Static classParsedateImplementsRunnable {inti = 0; PublicParsedate (inti) { This. i =i; } /*** When an object implementing interface <code>Runnable</code> was used * to create a Threa D, starting the thread causes the object ' s * <code>run</code> method to being called in that separately E xecuting * thread. * <p> * The general contract of the method <code>run</code> are that it could * take any AC tion whatsoever. * * @seeThread#run ()*/@Override Public voidrun () {Try { if(T1.get () = =NULL) T1.set (NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss")); Date T= T1.get (). Parse ("2015-03-29 19:29:" + i% 60); System.out.println (i+ ":" +t); } Catch(ParseException e) {e.printstacktrace (); } } } Public Static voidMain (string[] args) {Executorservice es= Executors.newfixedthreadpool (10); for(inti = 0; i < 1000; i++) {Es.execute (Newparsedate (i)); } }}
As you can see from here, assigning an object to each thread manually does not have to be threadlocal. But it needs to be guaranteed at the application level, if the same object instance is assigned to each thread on the application, then threadlocal does not guarantee thread safety.
Simple use of threadlocal (reading notes)