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") );
    }


  • 相关阅读:
    Delphi Excel 操作大全
    ThreadLocal类
    MyBatis实战总结
    MyBatis入门
    Mybatis逆向工程
    2020年全国高校计算机能力挑战赛初赛java组
    集合论基础
    命题与逻辑
    Redis技术概述
    UML图中6种箭头的含义
  • 原文地址:https://www.cnblogs.com/anxbb/p/8624786.html
Copyright © 2011-2022 走看看