在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 0
to 100
)传递给run()
方法。
我怎样才能做到这一点?