package com.lx.top;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class TestOne {
public static void main(String[] args) {
// 测试普通数组
demo (
() -> new int[10],
(array) -> array.length,
(array, index) -> array[index]++,
(array) -> {System.out.println(Arrays.toString(array));}
);
// 测试原子数组
demo (
() -> new AtomicIntegerArray(10),
(array) -> array.length(),
(array, index) -> array.getAndIncrement(index),
(array) -> {System.out.println(array);}
);
}
/**
* @param1 提供数组,可以是线程安全数组也可以是线程不安全数组
* @param2 获取数组长度的方法
* @param3 自增方法,回传 array & index
* @param4 打印数组的方法
*
* Supplier 提供者, 无中生有 () -> result
* Function 函数, 一个参数一个结果 (param) -> result, BiFunction (param1, param2) -> result
* Consumer 消费者,一个参数没结果 (param) -> void, BiConsumer (param1, param2) -> void
*/
@SuppressWarnings("unused")
private static <T> void demo(
Supplier<T> arraySupplier, // 原子数组和普通数组的创建方法不同,所以交给调用者创建
Function<T, Integer> lengthFun, // 原子数组和普通数组获取长度的方法不同,所以交给调用者
BiConsumer<T, Integer> putConsumer,
Consumer<T> printConsumer ) {
List<Thread> tList = new ArrayList<Thread>();
T array = arraySupplier.get();
int length = lengthFun.apply(array);
// 根据数组长度数创建线程
for (int i = 0; i < length; i++) {
// 每个线程对数组操作10000次
tList.add(new Thread(() -> {
for (int j = 0; j < 10000; j++) {
putConsumer.accept(array, j%length);
}
}));
}
// 启动所有线程
tList.forEach(t -> t.start());
// 等待所有线程运行结束
tList.forEach(t -> {
try {
t.join();
} catch (Exception e) {
e.printStackTrace();
}
});
printConsumer.accept(array);
}
}
原子数组使用
最新推荐文章于 2025-02-25 01:28:40 发布