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。該段代碼工作作爲寫不編譯罰款
因爲您的任務需要這樣的排序時間來完成它們在下一次循環迭代之前執行。你需要提供更多的工作線索 - 也許隨機睡眠。另請參見['invokeAll'](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection))。 –
您需要打印更多行。你正在處理競爭條件,線程正在完成得太快。 – Gray
我把Thread.sleep(60000),它仍然按照與Boris the Spider所說的相同的順序打印 – Popcorn