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