/*
函数式接口:
Supplier:()->返回值
function: (参数)->返回值 Bifunction: (参数1 ,参数2)->返回值
BiConsumer: (参数1,参数2)->void Consumer: (参数1)->void
*/
public class test {
private static <T> void demon(
Supplier<T> arraySupplier, //提供数组或者原子数组
Function<T,Integer> lengthFun, //获取提供数组的长度
BiConsumer<T,Integer>putConsumer, //自增
Consumer<T>printConsumer //打印提供的数组
) throws InterruptedException {
List<Thread> list=new ArrayList<>();
T array=arraySupplier.get();
int length=lengthFun.apply(array);
for (int i = 0; i <length ; i++) {
list.add(new Thread(()->{
for (int j=0;j<1000;j++){
putConsumer.accept(array,j%length);
}
}));
}
for (Thread t:list){
t.start();
}
for (Thread t:list){
t.join();
}
printConsumer.accept(array);
}
public static void main(String[] args) throws InterruptedException {
demon(()->new int[10],
(a)->a.length,
(a,index)->a[index]++,
(a)-> System.out.println(Arrays.toString(a)));
demon(
()->new AtomicIntegerArray(10),
(array)->array.length(),
(array,index)->array.getAndIncrement(index),
(a)-> System.out.println(a)
);
}
}
线程之原子数组(AtomicIntegerArray)
最新推荐文章于 2024-07-21 22:27:18 发布