4.3.1 ThreadLoacl简单使用

我们都知道  SimpleDateFormat 这个类是线程 不安全的,那么我下面的程序执行就会遇到问题

 

public class ParseDateDemo {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static class ParseDate implements Runnable {
int i = 0;

public ParseDate(int i) {
this.i = i;
}

public void run() {

try {
Date date = sdf.parse("2017-05-06 12:33:" + i % 60);
System.out.println(i + ":" + date);
} catch (ParseException e) {
e.printStackTrace();
}
}

}

public static void main(String args[]) {

ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 200; i++) {
executorService.execute(new ParseDate(i));
}
executorService.shutdown();
}
}

最常见的错误就是Exception in thread "pool-1-thread-32" java.lang.NumberFormatException: empty String
Exception in thread "pool-1-thread-22" java.lang.NumberFormatException: multiple points
那么如果我们还想使用这个类,但是还不想每次都新增应该怎么办呢,我们就可以使用TheadLoacl这个类,但是我们要确保这个类里面的类不是共享类,不然也存在线程安全问题。

public class ParseDateDemo {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static ThreadLocal<DateFormat> threadLocal=new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static class ParseDate implements Runnable {
int i = 0;

public ParseDate(int i) {
this.i = i;
}

public void run() {

try {
// Date date = sdf.parse("2017-05-06 12:33:" + i % 60);
Date date = threadLocal.get().parse("2017-05-06 12:33:" + i % 60);
System.out.println(i + ":" + date);
} catch (ParseException e) {
e.printStackTrace();
}
}

}

public static void main(String args[]) {

ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 200; i++) {
executorService.execute(new ParseDate(i));
}
executorService.shutdown();
}
}

另一种写法:如果不用初始化方法  也可以向我下面这样写,也能实现:

private static ThreadLocal<DateFormat> threadLocal=new ThreadLocal<DateFormat>(){

if(threadLocal.get()==null){
threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") );
}


转载于:https://www.cnblogs.com/anxbb/p/8624786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值