SimpleDateFormat is a common class in Java that is used to parse and format date strings, but it can cause very subtle and difficult-to-debug problems if you use carelessness.
Because the DateFormat and SimpleDateFormat classes are not thread-safe, calling the format () and Parse () methods in a multithreaded environment should use synchronous code to avoid problems.
Or you can use threadlocal to turn shared variables into exclusive, and thread-exclusive will definitely be able to reduce the overhead of creating objects in a concurrent environment in a concurrency-exclusive way.
This approach is generally recommended if performance requirements are high.
1 Public classDateutil {2 3 Static FinalDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");4 5 StaticThreadlocal<dateformat> ThreadLocal =NewThreadlocal<dateformat>() {6 protectedDateFormat InitialValue () {7 return NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");8 }9 };Ten One Private StaticDateFormat DateFormat () { A //return SDF; - returnthreadlocal.get (); - } the - Public StaticDate Parse (String datestr)throwsParseException { - returnDateFormat (). Parse (DATESTR); - } + - Public StaticString Format (date date) { + returnDateFormat (). Format (date); A } at - Public Static voidMain (string[] args) { - for(inti = 0; I < 3; i++) { - NewThread () { - Public voidrun () { - while(true) { in Try { -Thread.Sleep (2000); to}Catch(interruptedexception E1) { + e1.printstacktrace (); - } the * Try { $System.out.println ( This. GetName () + ":" + dateutil.parse ("2013-05-24 06:02:20"));Panax Notoginseng}Catch(ParseException e) { - e.printstacktrace (); the } + } A } the }.start (); + } -}
Reference:
Http://www.cnblogs.com/zemliu/p/3290585.html
Http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html
SimpleDateFormat thread safety issues and solutions