zoukankan      html  css  js  c++  java
  • 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") );
    }


  • 相关阅读:
    Reflector 已经out了,试试ILSpy
    visio studio删除空行
    SQL语句增加字段、修改字段、修改类型、修改默认值
    判断两个集合中 是否有相同的元素
    Rdlc 参数问题
    SQL Server 2008 报表服务入门【转】
    WebAPI异常捕捉处理,结合log4net日志(webapi2框架)
    HTTP Error 500.30
    前端Json 增加,删除,修改元素(包含json数组处理)
    IE浏览器F12调试模式不能使用或报错以及安装程序遇到错误0x80240037的解决办法
  • 原文地址:https://www.cnblogs.com/anxbb/p/8624786.html
Copyright © 2011-2022 走看看