可能重复:
for循环中的最终计数器?
下面是我目前正在运行的代码。我希望能够将迭代器 i 传递到新的 Runnable() 代码中。我知道我通常需要 make 变量 final 才能传递给内部类,但这会破坏迭代器的效果。我知道通常我可以尝试使 Runnable 内部类成为真正的类(请原谅我缺乏术语),但是我会失去 CountDownLatches 的效果。
private long generateThreads(int cores){
if (cores <= 0)
cores = Runtime.getRuntime().availableProcessors();
System.out.println("Using " + cores + " threads for processing");
final ExecutorService exec = Executors.newFixedThreadPool(cores);
final CountDownLatch ready = new CountDownLatch(cores);
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch done = new CountDownLatch(cores);
for (int i = 1; i <= cores; i++){
exec.execute(new Runnable(){
public void run(){
ready.countDown();
try{
start.await();
//do work
}
} catch (InterruptedException e){
Thread.currentThread().interrupt();
} finally{
done.countDown();
exec.shutdown();
}
}
});
}
long startTime = 0;
try{
ready.await();
startTime = System.nanoTime();
start.countDown();
done.await();
} catch (InterruptedException e){
e.printStackTrace();
}
return System.nanoTime() - startTime;
}
有谁知道给每个线程一个迭代器的方法,或者创建一个显示所有外部类成员的类,特别是 CountDownLatches?