2016-06-28 21 views
-1

我有一個人的陣列列表ArrayList<Person>。每個人隨機獲取它的名字和年齡。在PersonArrayList我用lambda表達式過濾了18歲。如何爲陣列列表的每個人創建一個線程

我的問題是我怎樣才能爲Arraylist的每個過濾Person創建Thread

我的代碼:

public class Person implements Runnable 
{ 
    private String name; 
    private int age; 

    public Person(String name, int age) { 
     this.name = name; 
     this.age = age; 
    } 

    public void run() { 
     // to fill up later 
    } 
} 

public class Main { 
     private static int nameCount = 1; 
     public static List<Person> list; 

     public static void main(String[] args) { 
      list = new ArrayList<Person>(); 
      for (int i = 0; i < 5; i++) { 
       list.add(new Person(getPersonName(), getPersonAge()); 
      } 
      list.removeIf(p -> p.getage().equals(18)); 
      for (Person person : list) { 
       System.out.println(persion); 
      } 
     } 

     public static String getPersonName() { 
      String nameto = "PERSON" + String.valueOf(nameCount); 
      nameCount++; 
      return nameto; 
     } 

     public static int getPersonAge() { 
      Random ran = new Random(); 
      int ageperson = ran.nextInt(25) + 1; 
      return ageperson; 
     } 
     //how to make an instance of Thread after filtering the person 
    } 
+6

SO的圖像編碼一般不太好。 – Timo

+1

歡迎來到SO :)關注@TimoSta建議,請修改您的問題並複製/粘貼您的代碼,而不是發佈屏幕截圖。 –

+0

'Person implements Runnable'的想法聽起來很奇怪。 「運行」一個人意味着什麼?當你想在後臺線程中對一個人做更多的事情時,這意味着什麼? –

回答

0

我與詹姆斯大同意,Person implements Runnable的想法聽起來很奇怪。

但是,任何方式來實現對列表中您可以使用StreamAPI和方法foreach每個項目的一些邏輯,我也推薦使用這種方法filter

那麼結果將是下一個:

list.stream() 
    .filter(person -> person.getage() == 18) 
    .forEach(person -> new Thread(person).start()); 
+0

我是否需要將它放在循環中?爲每個人創建一個線程? – ilovejavaAJ

+0

不,您不需要, forEach()方法調用流中每個元素的邏輯。 因此,在你的情況下,將爲每個元素創建一個線程並調用方法'start()'。 –