亲宝软件园·资讯

展开

Java并发排序 Java基于fork/koin类实现并发排序

---WeiGeH 人气:0

概述

主要谈一谈 Java使用fork/koin类 实现的并发排序 以及对于Stream流的支持的splitetor

奇数 x/2+1 11->6

偶数 x/2 10 ==>5

public class Use_Arrays {
   
  @Test
  public void test_mismatch() {
    int []x =new int[] {1,2,3,4};
    int []y =new int[] {1,3,4,5};
    int index = Arrays.mismatch(x, y);
    System.out.println(index);
  }
  
  @Test
  public void test_parallelPrefix() {
    int []x =new int[] {1,2,3,4};
    //f2=f1+f2
    //f3=f2+f3
    Arrays.parallelPrefix(x, (k,v)->k+v);
    System.out.println(Arrays.toString(x));
    
    // 实现1-100累加求和
    int []y =new int[100];
    Arrays.parallelSetAll(y, k->k=1);
    Arrays.parallelPrefix(y, (k,v)->k+v);
    System.out.println(Arrays.toString(y));
    
  }
  @Test
  public void test_parallelSetAll() {
    int []x =new int[100];
    x[0]=1;
    Arrays.parallelSetAll(x, y->y+1);
    System.out.println(Arrays.toString(x));
  }
  
  @Test
  public void test_parallSort() {
     IntStream stream = new Random().ints(0, 1000).limit(1000);
     int[] array = stream.toArray();
     System.out.println(Arrays.toString(array));
     Arrays.parallelSort(array);
     System.out.println(Arrays.toString(array));
  }
  
  @Test
  public void test_spliterator() {
    int []x =new int[11];
    Arrays.parallelSetAll(x, k->k+=1);
    System.out.println(Arrays.toString(x));
    
    Spliterator.OfInt int0_100 = Arrays.spliterator(x);
    
    int [] y=new int[(int) int0_100.estimateSize()];
    int i=0;
    System.out.println(int0_100.estimateSize());
    System.out.println(int0_100.characteristics());
    System.out.println(int0_100.getExactSizeIfKnown());
    
    //spliterator.forEachRemaining((int k)->System.out.println(k));
    
    OfInt int1_50 = int0_100.trySplit();
    OfInt int2_25 = int1_50.trySplit();
    int0_100.forEachRemaining((int k)->System.out.print(k+" "));
    System.out.println();
    int1_50.forEachRemaining((int k)->System.out.print(k+" "));
    System.out.println();
    int2_25.forEachRemaining((int k)->System.out.print(k+" "));
  }
}

2:使用Spliterator实现并行输出

@Test
  public void definied_Sort() {
     IntStream stream = new Random().ints(0, 100).limit(100);
     int[] array = stream.toArray();
     Arrays.sort(array);
     final int NUMS=3;// 切分的次数
     
     ExecutorService thread_pool = Executors.newFixedThreadPool(10);
     
     Spliterator.OfInt cut1 = Arrays.spliterator(array);
     while(!thread_pool.isTerminated()) {
       thread_pool.submit(()->{
          OfInt split = cut1.trySplit();
           thread_pool.shutdown();
         split.forEachRemaining((int k)->System.out.print(k+" "));
         System.out.println();
       });
     }
  }

加载全部内容

相关教程
猜你喜欢
用户评论