线程独享

http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

ThreadLocal 线程独享,synchronized 方法独享。

import java.text.ParseException;

public class TestSimpleDateFormat {
    
    public static class ThreadSafe extends Thread {
        @Override
        public void run() {
            while(true) {
                try {
                	System.out.println(this+"="+System.currentTimeMillis());
                    //自己等待自己2000毫秒,提高并发命中//调用线程
                	this.join(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                try {
                    System.out.println(this.getName()+":"+DateUtil.parse("2015-11-11 00:00:00"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }    
    }
    
    
    public static void main(String[] args) {
        for(int i = 0; i < 3; i++){
            new ThreadSafe().start();
        }
            
    }
}

 Exception in thread "Thread-1" java.lang.NumberFormatException: For input string: "20152015E4"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

at java.lang.Long.parseLong(Long.java:419)

at java.lang.Long.parseLong(Long.java:468)

at java.text.DigitList.getLong(DigitList.java:177)

at java.text.DecimalFormat.parse(DecimalFormat.java:1297)

at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)

at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311)

at java.text.DateFormat.parse(DateFormat.java:335)

at com.wnj.javausage.DateUtil.parse(DateUtil.java:17)

方式1

    private static ThreadLocal<DateFormat> sdf= new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public static Date parse(String dateStr) throws ParseException {
        return sdf.get().parse(dateStr);
    }

 方式2

    public static DateFormat getDateFormat() {  
        DateFormat df = threadLocal.get();  
        if(df==null){  
            df = new SimpleDateFormat(date_format);  
            threadLocal.set(df);  
        }  
        return df;  
    }  

    public static String formatDate(Date date) throws ParseException {
        return getDateFormat().format(date);
    }

猜你喜欢

转载自luckywnj.iteye.com/blog/2257887