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;
}
}
结果: