在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
(這是從0
到100
)傳遞給run()
方法。
我該怎麼做?