原子数组
package org.example;
import java.sql.Array;
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;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
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.toString())
);
}
private static <T> void demo(Supplier<T> arraySupplier, Function<T,Integer> lengthFunc, BiConsumer<T,Integer> putConsumer,
Consumer<T> printConsumer) {
List<Thread> ts = new ArrayList<>();
T array = arraySupplier.get();
int length = lengthFunc.apply(array);
for (int i = 0; i < length; i++) {
ts.add(new Thread(()->{
for(int j = 0;j<10000;j++) {
putConsumer.accept(array,j%length);
}
}));
}
ts.forEach(t->t.start());
ts.forEach(t-> {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
printConsumer.accept(array);
}
}