带有收集结果的java多线程循环

时间:2016-01-26 07:08:19

标签: java multithreading loops

抱歉有限的代码,因为我完全不知道如何做,部分代码不是代码,只是解释我需要什么。基数是:

arrayList<double> resultTopTen = new arrayList<double();
arrayList<double> conditions = new arrayList<double(); // this arrayList can be of a very large size milion+, gets filled by different code

double result = 0;

for (int i = 0, i < conditions.size(), i++){   //multithread this

loopResult = conditions.get(i) + 5; 

   if (result.size() < 10){
      resultTopTen.add(loopResult);
   }
   else{
      //this part i don't know, if this loopResult belongs to the TOP 10 loopResults so far, just by size, replace the smallest one with current, so that i will get updated resultTopTen in this point of loop. 

   }
} 
  • loopResult = conditions.get(i)+ 5;部分只是一个例子,计算是不同的,实际上它甚至不是双倍的,所以不可能简单地对条件进行排序并从那里开始。
  • for(int i = 0,i&lt; conditions.size(),i ++)part意味着我必须遍历输入条件列表,并执行计算并获得条件列表中每个条件的结果,不必完全有序。
  • 多线程部分是我真的不知道怎么做的事情,但是因为条件arrayList非常大,我想以某种方式并行计算它,好像我这样做就像它在代码中一样1个线程中的简单循环,我不会完全利用我的计算资源。这里的诀窍是如何分割条件,然后收集结果。为简单起见,如果我想在2个线程中进行,我会将条件分成两半,让1个线程为上半部分执行相同的循环,第二个为第二个,我会得到2个resultTopTen,我可以在之后放在一起,但是很多更好的方法是将事物拆分为系统资源提供的线程数(例如,直到cpu ut <90%,ram <90%)。那可能吗?

2 个答案:

答案 0 :(得分:1)

使用Java 8的并行流。

static class TopN<T> {

    final TreeSet<T> max;
    final int size;

    TopN(int size, Comparator<T> comparator) {
        this.max = new TreeSet<>(comparator);
        this.size = size;
    }

    void add(T n) {
        max.add(n);
        if (max.size() > size)
            max.remove(max.last());
    }

    void combine(TopN<T> o) {
        for (T e : o.max)
            add(e);
    }

}

public static void main(String[] args) {
    List<Double> conditions = new ArrayList<>();
    // add elements to conditions
    TopN<Double> maxN = conditions.parallelStream()
        .map(d -> d + 5)    // some calculation
        .collect(() -> new TopN<Double>(10, (a, b) -> Double.compare(a, b)),
            TopN::add, TopN::combine);
    System.out.println(maxN.max);
}

班级TopN包含T的前n项。

此代码打印conditions中的最小前10位(每个元素加5)。

答案 1 :(得分:-1)

让我简化您的问题,根据我的理解,请确认或添加:

要求:您希望从名为条件的列表中找到前10个结果。

过程:您希望多个线程处理您查找前10个结果的逻辑并累积结果以获得top10。

请同时分享你想要实现的逻辑以获得top10元素,或者它只是列表的降序以及它的前10个元素。