2014-12-01 88 views
0

在下面的代碼我試圖計算的次數execute方法被調用,但count不會增加:爲什麼在這個例子中var不會遞增?

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個'execute'調用也只增加一次'count'。 – 2014-12-01 16:24:24

+0

您是否每次看到'創建4,1個線程? – sp00m 2014-12-01 16:24:27

回答

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"); 

    } 
0

你重置在外環每次count。我不確定這是否是有意的。

相關問題