可以用同一个线程一一执行多个任务而不破坏和重新创建线程吗?

可以用同一个线程一一执行多个任务而不破坏和重新创建线程吗?


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");

    }

}


守着星空守着你
浏览 224回答 2
2回答

阿波罗的战车

ExecutorService executorService = Executors.newFixedThreadPool(5); 这将在Executor.&nbsp; for (int i = 0; i < 10; i++) {&nbsp; &nbsp; &nbsp; &nbsp; Runnable worker = new WorkerThread("" + i);&nbsp; &nbsp; &nbsp; &nbsp; executorService.execute(worker); // How many threads are created?&nbsp; &nbsp; }这将创建 10 个提交给执行程序服务执行的任务。ExecutorService 将使用固定的 5 个线程来执行这 10 个任务。所以是的,您将有一个线程执行多项任务而无需重新创建。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java