Java8 函数式编程、并发测试工具类

1、函数式编程

函数式编程是Java8的新特性,其实就是Lambda表达式的应用,详细介绍见:

Java 函数式接口 https://blog.csdn.net/qq_44537267/article/details/108812608

2、并发测试工具类

应用CountDownLatch类的一个简单测试工具类,关于CountDownLatch的用法介绍详见:

CountDownLatch用法简介 https://blog.csdn.net/weixin_44360895/article/details/115316857

2.1、自定义一个函数式接口
@FunctionalInterface
public interface ConcurrentTest {
    void test();
}
2.2、简易并发测试工具类
public class ConcurrentUtil {
    //threadNum为并发线程数
    public static void test(int threadNum, ConcurrentTest test){
        CountDownLatch count = new CountDownLatch(1);
        for (int i = 0; i < threadNum; i++) {
            new Thread(() -> {
                try {
                    count.await();
                    test.test();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
        System.out.println("并发开始!");
        count.countDown();
    }
}
2.3、测试使用

以测试SimpleDateFormat类线程不安全为例。
日期工具类:

public class DataUtil {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Date parseDate(String format){
        Date date = null;
        try {
            date = sdf.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

测试:

public class Test3 {
    public static void main(String[] args) {
        ConcurrentUtil.test(10, () -> {//10个线程并发
            final String[] strArr = new String[]{"2021-02-09 10:24:00", "2021-02-10 20:48:00", "2021-02-11 12:24:00"};
            int max = 2;
            int min = 0;
            Random random = new Random();
            int s = random.nextInt(max) % (max - min + 1) + min;
            System.out.println(Thread.currentThread().getName()+ "\t" + DataUtil.parseDate(strArr[s]));
        });
    }
}

结果:
在这里插入图片描述
改成LocalDataTime线程安全的类进行测试:

public class DataUtil {
    private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    public static LocalDateTime parseLocalDataTime(String format){
        LocalDateTime time = LocalDateTime.parse(format, df);
        return time;
    }
}

结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex·Guangzhou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值