2017-05-26 62 views
0

我想知道如果我可以在这种情况下多线程我的双循环。 在第二个循环中,我发送一个布尔值为true,如果某些条件完成并且我 在第一个循环中使用此布尔值的结果。在这种情况下多线程是否会破坏结果?如果没有,它会增加计算事件的速度吗?Multhreading Java double for循环与布尔内

这里是我的代码:

ArrayList<Appartement> sorted = new ArrayList<>(); 
boolean ispresent = false; 
for (Appartement p1: res2) { 
    ispresent = false; 
    for (Appartement p2: res2) { 
     if (p1.equals(p2)) 
      continue; 
      if (!p1.ContainNull() && !p2.ContainNull()){ 
      if (p1.getRoomCount().equals(p2.getRoomCount()) && p1.getPrice().equals(p2.getPrice()) && p1.getSurface().equals(p2.getSurface()) 
          && p1.getZipCode().equals(p2.getZipCode()) && p1.getNewBuild().equals(p2.getNewBuild()) 
          && p1.getPropertyType().equals(p2.getPropertyType()) && p1.getFurnished().equals(p2.getFurnished()) 
          && p1.getMarketingType().equals(p2.getMarketingType())) { 
         ispresent = true; 
         break; 
        } 
       } 
      } 
      if (!ispresent) 
       sorted.add(p1); 
    } 

我将在这里得到一些帮助。

+0

你为什么不试试看? –

+0

它看起来像你只想建立一个列表与所有独特的项目没有重复。实际上,你可以使用HashSet以O(n)的复杂度单次传递,所以你当然不需要多线程。 – BladeCoder

+0

我解析一个json文件,当我尝试使用HashSet时,它将所有我的公寓与重复在那里,所以我试过这种方式。我班的公寓有几个字符串值和int。 –

回答

0

所以你想创建一个新的线程来运行每个循环内的代码?如果你在目前的实现中这样做,它可能会中断,因为ispresent变量将在两个线程的范围内,这肯定会导致问题。

如果你把内部的循环在一个单独的类完全跑内部循环作为一个线程并把加入到ArrayList这样的伪代码,方法里面的护理:

class threadedLoop{ 
public void run() { 
     //Do your loopy stuff 
     //if ispresent then add to arraylist you passed as parameter 
    } 

    public static void main(String args[]) { 
     (new threadedLoop()).start(); 
    } 
} 

那么你将消除任何可能的冲突的风险,并应该看到你的程序的速度提高!看看here看看如何实现线程。

+0

谢谢,是的,我获得了一些时间,它并没有拧我的结果。 –

+0

很高兴帮助!如果这是你所寻找的,你能接受我的答案吗?非常感激 –