java并发编程——线程不安全的类

什么是线程不安全的类?

若是一个类的对象同时被多个线程访问,若是不作特殊的同步或并发处理,很容易表现出线程不安全的现象,好比抛出异常、逻辑处理错误等,这种类咱们就称为线程不安全的类。java

常见的线程不安全的类有哪些?

在此处主要讲解下SimpleDateFormat类以及JodaTime安全

SimpleDateFormat是线程不安全的类 例如:并发

public class DateFormatExample1 {
   private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
   public static int clientTotal = 1000;//请求总数

   private  static void update() throws ParseException {
       simpleDateFormat.parse("20181008");
   }

   public static void main(String[] args)throws Exception {
       ExecutorService executorService = Executors.newCachedThreadPool(); //定义线程池
       for (int i = 0; i < clientTotal; i++)
           executorService.execute(() -> {
               try {
                   update();
               } catch (ParseException e) {
                   e.printStackTrace();
               }
           });
   }
}

而解决这个问题的方法是能够采用堆栈封闭的方式maven

public class DateFormatExample2 {

   public static int clientTotal = 1000;//请求总数

   private  static void update() throws ParseException {
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
       simpleDateFormat.parse("20180208");
   }

   public static void main(String[] args)throws Exception {
       ExecutorService executorService = Executors.newCachedThreadPool(); //定义线程池
       for (int i = 0; i < clientTotal; i++)
           executorService.execute(() -> {
               try {
                   update();
               } catch (ParseException e) {
                   e.printStackTrace();
               }
           });
   }
}

而jodatime提供了一个DateTimeFormatter类,这个类是线程安全的,而且在实际应用中还有更多的优点。因此在实际的开发中推荐使用jodatime线程

使用时首先须要添加maven依赖包code

<dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time</artifactId>
   <version>2.9</version>
</dependency>
public class DateFormatExample2 {

   public static int clientTotal = 1000;//请求总数

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");

   private  static void update() throws ParseException {
       dateTimeFormatter.parseDateTime("20181008");
   }

   public static void main(String[] args)throws Exception {
       ExecutorService executorService = Executors.newCachedThreadPool(); //定义线程池
       for (int i = 0; i < clientTotal; i++)
           executorService.execute(() -> {
               try {
                   update();
               } catch (ParseException e) {
                   e.printStackTrace();
               }
           });
   }
}

参考地址:orm

相关文章
相关标签/搜索