Reputation: 53806
In below code I'm attempting to count the number of times the execute
method is invoked but count
is not incremented :
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
public class ThreadTest {
@Test
public void testThread() {
ExecutorService es = Executors.newCachedThreadPool();
for (int counter = 0; counter < 10; ++counter) {
int count = 0;
for (int i = 0; i < 4; i++) {
es.execute(new FooWorker());
}
count = count + 1;
System.out.println((count * 4) + "," + count + " threads created");
}
}
private final class FooWorker implements Runnable {
public void run() {
System.out.println("in run");
}
}
}
Why is count
not incremented ?
Upvotes: 0
Views: 79
Reputation: 13222
You are resetting count to 0 each iteration...
for (int counter = 0; counter < 10; ++counter) {
int count = 0; // count is reset to 0 every loop
for (int i = 0; i < 4; i++) {
es.execute(new FooWorker());
}
count = count + 1; // count will always be 1 here
System.out.println((count * 4) + "," + count + " threads created");
}
Upvotes: 4
Reputation: 39457
You're resetting count
each time in the outer loop. I am not sure if that's intended.
Upvotes: 0