Possible Duplicate:
A final counter in a for loop?
Below is the code I'm currently running. I'd like to be able to pass the iterator i into the new Runnable() code. I know I usually need the make variables final in order to pass into an inner class, but that ruins the effect of the iterator. I know normally I could try to make the Runnable inner class a true class (excuse my lack of terminology), but then I'd lose the effects of the 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;
}
Does anyone know of a way to give each thread the iterator, or create a class that shows all of the outer class members, particularly the CountDownLatches?