2013-03-20 109 views
0

在Java中,我有一個代碼:創建對象與Java

Graph[] graphs = new Graph[100]; 
for (int i = 0; i < 100; i++) { 
    graphs[i] = new Graph(); 
    Graph g = graphs[i]; 
    g.subgraphs = new Graph[100 - i]; 
    g.leaves = new HashSet<Integer>(); 
    g.targets = new HashMap<Integer, int[]>(l - i); 
    g.weights = new HashMap<Integer, Integer>(l - i); 
} 

我希望寫一個並行代碼。您可以在這裏幫助我學習Java線程。所以我添加以下代碼:

Thread[] threads = new Thread[3]; 
for (int i = 0; i < threads.length; i++) { 
    threads[i] = new Thread(new Runnable() { 
     public void run() { 
      // some code to run in parallel 
     } 
    }); 
    threads[i].start(); 
} 

// as far as I understood this waits until threads above are finishing 
for (int i = 0; i < threads.length; i++) { 
    try { 
     threads[i].join(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

現在我可以將代碼從循環複製,當我創建我的自定義Graph對象,但我需要以某種指數i(這是從0100)傳遞給run()方法。

我該怎麼做?

回答

1

Java你只能從匿名內部類引用final領域,所以你需要聲明一個final變量j訪問索引:

Thread[] threads = new Thread[3]; 
for (int i = 0; i < threads.length; i++) { 
    final int j = i; 
    threads[i] = new Thread(new Runnable() { 
    public void run() { 
     // some code to run in parallel 
     System.out.println(j); 
    } 
    }); 
    threads[i].start(); 
} 
2

如果你的目標是最大限度地提高性能,那麼你最好的選擇就是這裏沒有任何並行性。創建幾百個HashMap幾乎肯定會比啓動任何新線程便宜。

1

我知道的多線程不適合實例化對象,但我支持你親自練習編碼技巧。所以只要嘗試一下並從實際結果中汲取教訓。

實際上,自從Java SE 1.5以來,很少使用低級多線程代碼。因爲併發包出現了。嘗試學習ExecutorExecutorServiceCompletionService

請參閱Perform N tasks in parallelUnderstanding java.util.concurrent.CompletionService