为什么var在这个例子中没有增加?

时间:2014-12-01 16:22:38

标签: java multithreading

在下面的代码中,我试图计算调用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没有增加?

2 个答案:

答案 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。我不确定这是不是有意。