在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
到 100
) 到 run()
方法。
我怎样才能做到这一点?
最佳答案
如果您的目标是最大限度地提高性能,那么您最好的选择几乎肯定是这里完全不进行并行。创建几百个 HashMap
几乎肯定比启动任何新线程更便宜。
关于java - 与 Java 并行创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513091/