【7】 常见线程不安全的类与写法

版权声明:送人玫瑰,手有余香,一分也是爱 https://blog.csdn.net/m0_37156901/article/details/86010853

 StringBuilder 不安全

StringBuilder 不安全,但是可以放在方法内局部变量,是堆栈封闭的,

StrinBuffer  安全

synchronized关键字性能损耗,

查看append方法:stringBuffer.append("h");

SimpleDateFormat 不安全,除非定义局部变量堆栈封闭

  public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void dateCall(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            simpleDateFormat.parse("20180903");
        } catch (ParseException e) {
            log.info("解析日期异常");
            e.printStackTrace();
        }
    }

joda-time -SimpleDateFormat- 安全的日期包

    <!--安全的日期类-->
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
	<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.9</version>
		</dependency>

实现代码

package com.mmall.concurrency.unsafeClass;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class jodaDateTime {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    //  jodaTime
    // public static DateTimeFormatter dateTimeFormatter = new DateTimeFormatter("yyyyMMdd");
    public static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");

    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            final int count = i;
            executorService.execute( () -> {
                // 线程里执行,加解锁,中间执行
                try {
                    semaphore.acquire();
                    dateCall(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();

    }

    private static void dateCall(int j){
        log.info("{},{}",j, DateTime.parse("20190723",dateTimeFormatter));
    }
}
jodaDateTime - 4165,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4054,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4046,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4167,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4050,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4169,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4161,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4170,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4033,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4113,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4138,2019-0

最常用的集合数据结构-- 当然有对应安全的


@Slf4j
@NotThreadSafe
public class HashSetDemo {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static Set<Integer> set = new HashSet<>();

    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            final int count = i;
            executorService.execute( () -> {
                // 线程里执行,加解锁,中间执行
                try {
                    semaphore.acquire();
                    hash(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();
        log.info("set不安全:{}",set.size());
    }

    private static void hash(int j){
        set.add(j);
    }
}

接下来看看那些不安全的写法

两个线程同时判断-同时符合-同时处理-线程安全问题

因为两个操作之间有间隔,不是原子性

结局办法 -- 加个锁-  原子性 -- CAS

总结:

*  这几个写法查资料单独学习

ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

*  除了上面提到的几个类,还有很多线程不安全的类

猜你喜欢

转载自blog.csdn.net/m0_37156901/article/details/86010853