在下面的代码中,我试图计算调用execute
方法但count
未递增的次数:
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");
}
}
}
为什么count
没有增加?
答案 0 :(得分:4)
您每次迭代都会将计数重置为0 ......
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");
}
答案 1 :(得分:0)
每次在外循环中重置count
。我不确定这是不是有意。