2013-03-20 65 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