0

在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(即 from 0to 100)传递给run()方法。

我怎样才能做到这一点?

4

3 回答 3

2

如果您的目标是最大化性能,那么您最好的选择几乎可以肯定是这里根本不做并行。创建几百个HashMaps 几乎肯定会比启动任何新线程便宜。

于 2013-03-20T00:29:18.023 回答
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();
}
于 2013-03-20T01:27:20.663 回答
1

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

实际上,从 Java SE 1.5 开始,很少使用低级多线程代码。因为并发包出现了。尝试向ExecutorExecutorService学习CompletionService

请参阅并行执行 N 个任务了解 java.util.concurrent.CompletionService

于 2013-03-20T01:53:54.607 回答