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。这段代码工作正常
最佳答案
您编写的代码无法编译。我猜你在代码中还有一些你没有在这里剪切/粘贴的东西。这是您为编译而编写的代码。我测试了它,它对我有用。您的实际代码和下面的代码有什么区别? (请原谅“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();
}
}
关于java - 为什么我的线程不能使用 Java ExecutorService 并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21102759/