6
public class Test { 
    private ExecutorService executor = Executors.newFixedThreadPool(50); 

    public void startTenThreads() { 
     for (int i = 0; i < 10; i++) { 
      executor.execute(new FooWorker(i)); 
     } 
    } 

    private final class FooWorker implements Runnable { 
     private int threadNum; 

     public FooWorker(int threadNum) { 
      this.threadNum = threadNum; 
     } 

     public void run() { 
      System.out.println("Thread " + threadNum + " starting"); 
      Thread.sleep(60000); 
      System.out.println("Thread " + threadNum + " finished"); 
     } 
    } 
} 

我想這些線程並行運行,但是輸出顯示它不是並行運行,而是按順序:爲什麼我的線程不能使用Java ExecutorService並行運行?

Thread 1 starting 
Thread 1 finished 
Thread 2 starting 
Thread 2 finished 
Thread 3 starting 
Thread 3 finished 
Thread 4 starting 
Thread 4 finished 
Thread 5 starting 
Thread 5 finished 
... 

我在做什麼錯?

編輯:發現問題,有人已經建立線程池的大小爲1。該段代碼工作作爲寫不編譯罰款

+4

因爲您的任務需要這樣的排序時間來完成它們在下一次循環迭代之前執行。你需要提供更多的工作線索 - 也許隨機睡眠。另請參見['invokeAll'](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection))。 –

+0

您需要打印更多行。你正在處理競爭條件,線程正在完成得太快。 – Gray

+0

我把Thread.sleep(60000),它仍然按照與Boris the Spider所說的相同的順序打印 – Popcorn

回答

1

您的代碼。我猜你在代碼中還有其他的東西,你沒有在這裏剪切/粘貼。這裏是你編寫的代碼來編譯。我測試了它,它適用於我。你的實際代碼和下面的代碼有什麼區別? (請原諒「TheadTest」中的錯字)。

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class TheadTest { 

    private ExecutorService executor = Executors.newFixedThreadPool(50); 

    public void startTenThreads() { 
     for (int i = 0; i < 10; i++) { 
      executor.execute(new FooWorker(i)); 
     } 
    } 

    private final class FooWorker implements Runnable { 
     private int threadNum; 

     public FooWorker(int threadNum) { 
      this.threadNum = threadNum; 
     } 

     public void run() { 
      try { 
       System.out.println("Thread " + threadNum + " starting"); 
       Thread.sleep(60000); 
       System.out.println("Thread " + threadNum + " finished"); 
      } 
      catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     TheadTest tt = new TheadTest(); 
     tt.startTenThreads(); 
    } 

} 
+0

有很多不同之處,所以我不認爲我可以將它全部粘貼。我仍然試圖弄清楚這一點,但要點是我使用apache http客戶端發送http請求,並且我希望它們全部並行運行。我認爲這可能與使用HttpClient而不是AsyncHttpClient有關。仍在研究它 – Popcorn

相關問題