与Java并行创建对象

时间:2013-03-20 00:28:13

标签: java multithreading

在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(从0到{{1} })到100方法。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

如果您的目标是最大限度地提高性能,那么您最好的选择几乎肯定是根本没有并行性。创建几百HashMap几乎肯定会比启动任何新线程更便宜。

答案 1 :(得分: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 :(得分:1)

我知道多线程不适合实例化对象,但我支持你亲自练习编码技巧。所以试试吧,从实际结果中学习。

实际上,自Java SE 1.5以来,很少使用低级多线程代码。因为并发包出现了。尝试向ExecutorExecutorServiceCompletionService学习。

请参阅Perform N tasks in parallelUnderstanding java.util.concurrent.CompletionService