这是一个其中多个线程使用共享程序的程序
SimpleDateFormat。
程序:
public static void main(String[] args) throws Exception { final DateFormat format = new SimpleDateFormat("yyyyMMdd"); Callable<Date> task = new Callable<Date>(){ public Date call() throws Exception { return format.parse("20101022"); } }; //pool with 5 threads ExecutorService exec = Executors.newFixedThreadPool(5); List<Future<Date>> results = new ArrayList<Future<Date>>(); //perform 10 date conversions for(int i = 0 ; i < 10 ; i++){ results.add(exec.submit(task)); } exec.shutdown(); //look at the results for(Future<Date> result : results){ System.out.println(result.get()); }}
运行几次,你将看到:
例外情况:
这里有一些例子:
1。
Caused by: java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:431) at java.lang.Long.parseLong(Long.java:468) at java.text.DigitList.getLong(DigitList.java:177) at java.text.DecimalFormat.parse(DecimalFormat.java:1298) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)
2。
Caused by: java.lang.NumberFormatException: For input string: ".10201E.102014E4" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224) at java.lang.Double.parseDouble(Double.java:510) at java.text.DigitList.getDouble(DigitList.java:151) at java.text.DecimalFormat.parse(DecimalFormat.java:1303) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)
3。
Caused by: java.lang.NumberFormatException: multiple points at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1084) at java.lang.Double.parseDouble(Double.java:510) at java.text.DigitList.getDouble(DigitList.java:151) at java.text.DecimalFormat.parse(DecimalFormat.java:1303) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1936) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1312)
错误的结果:
Sat Oct 22 00:00:00 BST 2011Thu Jan 22 00:00:00 GMT 1970Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Thu Oct 22 00:00:00 GMT 1970Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010
正确的结果:
Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010Fri Oct 22 00:00:00 BST 2010
在多线程环境中安全使用DateFormats的另一种方法是使用 ThreadLocal变量来保存DateFormat 对象,这意味着每个线程将拥有自己的副本,而无需等待其他线程释放它。这是这样的:
public class DateFormatTest { private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){ @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; public Date convert(String source) throws ParseException{ Date d = df.get().parse(source); return d; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)