在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
方法。
我该怎么做?
答案 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以来,很少使用低级多线程代码。因为并发包出现了。尝试向Executor
,ExecutorService
和CompletionService
学习。
请参阅Perform N tasks in parallel和Understanding java.util.concurrent.CompletionService