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");
}
}
}
我希望这些线程能够并行运行,但输出显示它并没有并行运行,而是顺序运行:
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
方法。 - Boris the Spidersynchronized
。 - Boris the Spider