Java并发编程—— 线程不安全类与写法

一.概念

1.线程不安全的类:

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

2.线程不安的操作

先检查在执行:if( conditon(a) ){ handle(a) }

上述操作,并发问题可能会出现在检查与执行的间隙中,即便检查和执行都是线程安全的操作,但是放到一起就不属于线程安全操作;


二. StringBuilder【线程不安全】和StringBuffer【线程安全】对比

1.两者同时存在的意义:

在只考虑运行效率而不担心线程安全情况的时候,优先选择StringBuilder,执行效率快;在考虑线程安全的时候,优先选择StringBuffer

2.StringBuilder线程不安全】

  • StringBuilder线程不安全代码演示:
@Slf4j
public class StringExample1 {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static StringBuilder  stringBuilder = new StringBuilder();

    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++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", stringBuilder.length());
    }

    private static void update() {
        stringBuilder.append("1");
    }
}

3.StringBuffer【线程安全】

  • StringBuffer线程安全代码演示:
@Slf4j
@NotThreadSafe
public class StringExample2 {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static StringBuffer  stringBuffer = new StringBuffer();

    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++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", stringBuffer.length());
    }

    private static void update() {
        stringBuffer.append("1");
    }
}

3.StringBuffer线程安全的原因

  • StringBuffer之所以会是线程安全,是因为StringBuffer内的方法都加上了synchronized关键字,如下是 StringBufferappend()`源码所示:
    ...
   @Override
   public synchronized StringBuffer append(String str) {
       toStringCache = null;
       super.append(str);
       return this;
   }

   @Override
   public synchronized int length() {
       return count;
   }
   
   @Override
   public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
                                     int dstBegin)
   {
       super.getChars(srcBegin, srcEnd, dst, dstBegin);
   }
   .....

StringBuffer 线程安全,其方法有 synchronized 关键字修饰, 每次只能让一个线程来使用, 这样势必就会在性能上有所损失


三、SimpleDateFormatJodaTime

1. SimpleDateFormat介绍:

  • SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类,它允许进行格式化(日期→文本)、解析(文本→日期)和规范化。SimpleDateFormat 使得可以选择任何用户定义的日期/时间格式的模式。

2. SimpleDateFormat【线程不安全】

线程不安全的代码示例:

@Slf4j
@NotThreadSafe
public class DateFormatExample1 {

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;


    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++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void update() {
        try {
            simpleDateFormat.parse("20191025");
        } catch (ParseException e) {
            log.info("parse exception");
        }
    }
}

控制台输出得到结果如下:

java.lang.NumberFormatException: multiple points
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1867)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.mmall.concurrency.example.commonUnsafe.DateFormatExample1.update(DateFormatExample1.java:51)
	at com.mmall.concurrency.example.commonUnsafe.DateFormatExample1.lambda$main$0(DateFormatExample1.java:37)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
19:27:53.973 [pool-1-thread-2] ERROR com.mmall.concurrency.example.commonUnsafe.DateFormatExample1 - exception
java.lang.NumberFormatException: For input string: ".101101EE22"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1867)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.mmall.concurrency.example.commonUnsafe.DateFormatExample1.update(DateFormatExample1.java:51)
	at com.mmall.concurrency.example.commonUnsafe.DateFormatExample1.lambda$main$0(DateFormatExample1.java:37)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
	....

原因:SimpleDateFormat不是一个线程安全的类

3.使SimpleDateFormat线程安全的策略

方法:利用堆栈封闭的特性,实现线程安全;即声明一个局部变量的SimpleDateFormat对象来使用,上述代码修改为:

@Slf4j
@ThreadSafe
public class DateFormatExample2 {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;


    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++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void update() {
        try {
        //将SimpleDateFormat 声明到局部方法中,
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            simpleDateFormat.parse("20191025");
        } catch (ParseException e) {
            log.info("parse exception");
        }
    }
}

代码执行后不会抛出任何异常

4.JodaTime【线程安全】

介绍:
  • joda-time能够便捷地格式化时间输出、设定时间、加减时间、计算时间差值;
  • joda-time中的DateTime不仅线程安全,而且执行时间操作的时候,非常的便捷;
使用:
  • Maven依赖
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9</version>
        </dependency>
线程安全的代码示例:
@Slf4j
@ThreadSafe
public class DateFormatExample3 {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    private 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+1;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void update(int i) {
        log.info("{},{}",i,DateTime.parse("20191025",dateTimeFormatter).toDate());

    }
}

上述代码运行结果,不会按顺序输出,但是输出总数为5000条日志,与期望的结果一致,如下所示:

...
20:38:45.135 [pool-1-thread-2929] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 4998,Fri Oct 25 00:00:00 CST 2019
20:38:45.135 [pool-1-thread-2932] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 4999,Fri Oct 25 00:00:00 CST 2019
20:38:45.135 [pool-1-thread-2934] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 5000,Fri Oct 25 00:00:00 CST 2019
20:38:45.135 [pool-1-thread-3530] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 4700,Fri Oct 25 00:00:00 CST 2019
20:38:45.135 [pool-1-thread-3527] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 4696,Fri Oct 25 00:00:00 CST 2019
20:38:45.135 [pool-1-thread-3525] INFO com.mmall.concurrency.example.commonUnsafe.DateFormatExample3 - 4691,Fri Oct 25 00:00:00 CST 2019
...

四、ArrayListHashSetHashMapCollections【线程不安全】

日常中我们使用它们的时候,经常是声明在方法里面,作为局部变量来使用,一般很少会触发线程不安的问题。但是如果将它们定义为static时,且多个线程同时访问时,就容易出现并发的问题。它们有多个线程安全的类与之对应,后续文章继续补充。

1. ArrayList并发

示例代码如下:

@Slf4j
public class ArrayListExample {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    private static List<Integer> list = new ArrayList<>();

    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();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}" ,list.size());
    }

    private static void update(int i) {
        list.add(i);

    }
}
运行结果如下,并不是期望的5000;
11:53:24.250 [main] INFO com.mmall.concurrency.example.commonUnsafe.ArrayListExample - size:4993

Process finished with exit code 0

2. HashSet并发

示例代码如下:

@Slf4j
public class HashSetExample {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    private 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();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}" ,set.size());
    }

    private static void update(int i) {
        set.add(i);

    }
}
运行结果如下,也不是期望的5000;
11:59:04.893 [main] INFO com.mmall.concurrency.example.commonUnsafe.HashSetExample - size:4989

Process finished with exit code 0

3. HashMap并发

示例代码如下:

@Slf4j
@NotThreadSafe
public class HashMapExample {

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

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    private static Map<Integer,Integer> map = new HashMap<>();

    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();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}" ,map.size());
    }

    private static void update(int i) {
        map.put(i,i);

    }
}
运行结果如下,也不是期望的5000;
12:05:03.629 [main] INFO com.mmall.concurrency.example.commonUnsafe.HashMapExample - size:4981

Process finished with exit code 0

Java并发编程学习系列

如有帮助,烦请点赞收藏一下啦 (◕ᴗ◕✿)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值