当前位置:网站首页>JUC atomic array

JUC atomic array

2022-06-13 09:05:00 Q z1997

JUC An array of atoms

AtomicIntegerArray

  • AtomicLongArray
  • AtomicReferenceArray
/**  Parameters 1, Provide arrays 、 It can be a thread unsafe array or a thread safe array   Parameters 2, Method to get the length of the array   Parameters 3, Self increasing method , Comes back  array, index  Parameters 4, How to print an array  */
// supplier  Provider   Out of thin air  ()-> result 
// function  function   One parameter, one result  ( Parameters )-> result  , BiFunction ( Parameters 1, Parameters 2)-> result 
// consumer  consumer   A parameter has no result  ( Parameters )->void, BiConsumer ( Parameters 1, Parameters 2)->
private static <T> void demo(
 Supplier<T> arraySupplier,
 Function<T, Integer> lengthFun,
 BiConsumer<T, Integer> putConsumer,
 Consumer<T> printConsumer ) {
    
 List<Thread> ts = new ArrayList<>();
 T array = arraySupplier.get();
 int length = lengthFun.apply(array);
 for (int i = 0; i < length; i++) {
    
 //  Each thread is grouped in pairs  10000  operations 
 ts.add(new Thread(() -> {
    
 for (int j = 0; j < 10000; j++) {
    
 putConsumer.accept(array, j%length);
 }
 }));
 }
 ts.forEach(t -> t.start()); //  Start all threads 
 ts.forEach(t -> {
    
 try {
    
 t.join();
 } catch (InterruptedException e) {
    
 e.printStackTrace();
 }
 }); //  When all threads end 
 printConsumer.accept(array);
}

Unsafe array

demo(
 ()->new int[10],
 (array)->array.length,
 (array, index) -> array[index]++,
 array-> System.out.println(Arrays.toString(array))
);

Safe array

demo(
 ()-> new AtomicIntegerArray(10),
 (array) -> array.length(),
 (array, index) -> array.getAndIncrement(index),
 array -> System.out.println(array)
);
原网站

版权声明
本文为[Q z1997]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130859553773.html