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

什么是线程不安全的类?

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

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

79a1e8bfd2c0d0f526183bf652d24f96.png

在此处主要讲解下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();

}

});

}

}

69460a5722ce0023397f51ea3e810c7d.png

而解决这个问题的方法是可以采用堆栈封闭的方式

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依赖包

joda-time

joda-time

2.9

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();

}

});

}

}

参考地址:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值