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


  • 相关阅读:
    使用lua给wireshark编写uTP的Dissector
    Win32下 Qt与Lua交互使用(四):在Lua脚本中自由执行Qt类中的函数
    Win32下 Qt与Lua交互使用(三):在Lua脚本中connect Qt 对象
    Win32下 Qt与Lua交互使用(二):在Lua脚本中使用Qt类
    C# 自动部署之附加数据库
    机器码农:深度学习自动编程
    Oracle 记录插入时“Invalid parameter binding ”错误
    Visual Studio 在调试时启用编辑功能
    航摄比例尺与成图比例尺
    maven引用net.sf.json-lib
  • 原文地址:https://www.cnblogs.com/anxbb/p/8624786.html
Copyright © 2011-2022 走看看