可以用同一个线程一一执行多个任务而不破坏和重新创建线程吗?public class SimpleThreadPool { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("" + i); executorService.execute(worker); // How many threads are created? } executorService.shutdown(); while (!executorService.isTerminated()) { } System.out.println("All threads Executed"); }}
2 回答
阿波罗的战车
TA贡献1862条经验 获得超6个赞
ExecutorService executorService = Executors.newFixedThreadPool(5); 这将在Executor.
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executorService.execute(worker); // How many threads are created?
}
这将创建 10 个提交给执行程序服务执行的任务。ExecutorService 将使用固定的 5 个线程来执行这 10 个任务。所以是的,您将有一个线程执行多项任务而无需重新创建。
添加回答
举报
0/150
提交
取消