2016-03-07 37 views
0

我想要從Thread繼承的對象的集合;每個對象都在它自己的線程中運行。作爲對象的線程Java

我試過extends Thread並且叫super()認爲會確保創建一個新的線程;但沒有...只有main是正在運行的線程:(

每個人都告訴我,「實施Runnable把你想要的代碼在run()並把它放在一個線程對象」。 我不能這樣做,因爲這2,原因:

  1. 我的集合元素是不是型Thread,如果I多我不得不改變所有它的依賴

  2. run()不能包含整個類。 ..對吧?

所以我首先想知道的是,如果我想要做的甚至是可能的,其次,如果是的話,怎麼做呢?

+0

歡迎回來Olivier10178。 run()可以包含一個內部類。 –

+0

你能提供一些更多的信息嗎?當然,你可以擴展線程?然後你需要調用Thread.start()來使它們運行。 – starf

+0

你通常應該避免擴展'Thread'。你想達到什麼目的?爲什麼你不能將'Runnable's傳遞給'Thread'? – SLaks

回答

1

super()只是調用父構造函數(在你的情況下,默認Thread構造函數)。實際啓動新線程的方法是start()。正如其他人所說,擴展Thread的設計很糟糕。

是的,你可以創建一個實現Runnable

class MySpecialThread implements Runnable { 
    public void run() { 
     // Do something 
    } 
} 

一類,你可以在一個新的線程像這樣啓動它:

Thread t = new Thread(new MySpecialThread()); 
// Add it to a collection, track it etc. 
t.start(); // starts the new thread 

1 - 您可以使用Runnables或集合Thread的集合使用下面的示例。

MySpecialThread m = new MySpecialThread(); 
List<Runnable> runnables = new ArrayList<Runnable>(); 
runnables.add(m); 
List<Thread> threads = new ArrayList<Thread>(); 
threads.add(new Thread(m)); 

2-甲方法不能包含一類,但上述例子MySpecialThread是行爲類似的任何其它類的類。你可以寫一個構造函數中添加方法和字段等

+0

所以我需要一個單獨的列表來包含線程就是你說的。我不能只有一個列表的對象相當於線程? – Olivier10178

+0

我只是說你可以選擇。如果你想要一個'Thread'對象的列表,你不需要'Runnable'的列表。我只是表明這兩種選擇都是可能的。 – Samuel

+0

如果我只有一個Runnable列表;那麼我怎麼開始線程? – Olivier10178

0

我建議使用ExecutorService

讓我們對使用示例代碼ExecutorService

import java.util.*; 
import java.util.concurrent.*; 

public class ExecutorServiceDemo { 

    public static void main(String args[]){ 
     ExecutorService executor = Executors.newFixedThreadPool(10); 
     List<Future<Integer>> list = new ArrayList<Future<Integer>>(); 

     for(int i=0; i< 10; i++){ 
      CallableTask callable = new CallableTask(i+1); 
      Future<Integer> future = executor.submit(callable); 
      list.add(future); 
     } 
     for(Future<Integer> fut : list){ 
      try { 
       System.out.println(fut.get()); 
      } catch (InterruptedException | ExecutionException e) { 
       e.printStackTrace(); 
      } 
     } 
     executor.shutdown(); 
    } 
} 

class CallableTask implements Callable<Integer>{ 
    private int id = 0; 
    public CallableTask(int id){ 
     this.id = id; 
    } 
    public Integer call(){ 
     // Add your business logic 
     return Integer.valueOf(id); 
    } 
} 

輸出:

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

如果你想使用線程而不是ExecutorService,下面的代碼應該適合你。

import java.util.*; 

class MyRunnable implements Runnable{ 
    private int id = 0; 
    public MyRunnable(int id){ 
     this.id = id; 
    } 
    public void run(){ 
     // Add your business logic 
     System.out.println("ID:"+id); 
    } 
} 
public class RunnableList{ 
    public static void main(String args[]){ 
     List<Thread> list = new ArrayList<Thread>(); 
     for (int i=0; i<10; i++){ 
      Thread t = new Thread(new MyRunnable(i+1)); 
      list.add(t); 
      t.start(); 
     } 
    } 
} 
+0

爲什麼要有RunnableList? – Olivier10178