首页  

SimpleDateFormat并发问题实例演示     所属分类 java 浏览量 773
SimpleDateFormat 非线程安全,不能并发使用 


import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; public class SimpleDateFormatTest { static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; static final SimpleDateFormat sdf = new SimpleDateFormat(FORMAT); static final int TASK_COUNT = 3; final static AtomicLong formatError = new AtomicLong(0); final static AtomicLong parseError = new AtomicLong(0); final static AtomicLong success = new AtomicLong(0); static volatile String formatErrorInfo = null; static volatile String parseErrorInfo = null; public static void main(String[] args) throws Exception { for (int i = 0; i < TASK_COUNT; i++) { Thread task = new FormatAndParseTask(); task.start(); } while (true) { Thread.sleep(3000); System.out.println(success + " " + formatError + " " + parseError); System.out.println(formatErrorInfo); System.out.println(parseErrorInfo); System.out.println(); } } private static class FormatAndParseTask extends Thread { public void run() { while (true) { Date time1 = new Date(); String str = null; try { str = sdf.format(time1); } catch (Throwable e) { formatError.incrementAndGet(); formatErrorInfo = "formatError:" + e; // System.out.println("format error,"+e); continue; } Date time2 = null; try { time2 = sdf.parse(str); } catch (Throwable e) { parseError.incrementAndGet(); parseErrorInfo = "parseError:" + e; // System.out.println("parse error,"+e); continue; } success.incrementAndGet(); } } } }
601627 79 42592 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: "" 1606037 216 126336 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: "" 2552992 399 211061 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: ".2001E32001" 2557761 7496216 211440 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: "" 2557761 14828661 211440 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: "" 2557761 22464674 211440 formatError:java.lang.ArrayIndexOutOfBoundsException parseError:java.lang.NumberFormatException: For input string: ""
完整代码 https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/SimpleDateFormatTest.java

上一篇     下一篇
string format几种方式

字符串格式化性能对比

单元测试 AIR 和 FIRST 原则

云服务器jdk8安装

轻量应用服务器和云服务器的区别

家常臊子面做法