有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用ExecutorService/ThreadPool创建始终活动线程的简单变量列表

我在争论是否有必要将ExecutorService用于一个简单的、动态增长的同一类线程列表,所有线程都始终处于活动状态。我知道Executors.newFixedThreadPool(int)提供了一个线程池,它可以包含任意数量的线程,但在任何时间点,只有方法中指定的数量是活动的。我没有这样的限制,如果我添加6个线程,我希望所有6个线程同时运行

如果使用Executors框架有好处的话,我应该继续使用它,还是应该简单地将线程放在ArrayList中


共 (1) 个答案

  1. # 1 楼答案

    Should I still use the Executors framework, if there are advantages to using it, or should I simply put my threads in an ArrayList?

    很多人用叉子叉和管理自己的线程。然而,ExecutorService类被大力推荐的主要原因是它们负责线程和相关任务的管理,并减少您必须编写、调试和维护的代码量。显然,它们提供了许多其他功能,如Callable支持、完成服务等,您可能不会使用这些功能。但将管理工作交给这些核心类,即使是对于简单的项目,这本身也是一件好事。我甚至将它们用于单线程池,因为我希望线程池的Runnable任务队列特性,而不是编写自己的BlockingQueue或其他机制

    if I add 6 threads, I want all 6 to be running concurrently.

    然后您应该使用Executors.newCachedThreadPool()。如果您向它提交6个作业(实例RunnableCallable),那么将启动6个线程来处理它们。如果其中3个作业完成并提交了其他作业,则3个休眠线程将运行其他作业

    注意:如果您提交1000个作业,您将启动1000个线程,这很可能是而不是您想要做的事情


    例如,要自己编写这篇文章需要更多的代码:

    // a pool of 10 threads
    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    // submit a bunch of jobs to they 10 threads for processing
    for (MyJob job : jobsToDo) {
       threadPool.submit(job);
    }
    // no more tasks are being submitted so shutdown the pool
    threadPool.shutdown();
    // wait for the jobs to finish
    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);