如何懒惰地创建Java线程池使用的任务 [英] How to lazily create tasks for use by a Java thread-pool

查看:70
本文介绍了如何懒惰地创建Java线程池使用的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写一个负载测试应用程序,并且具有一个线程池,该线程池针对被测服务器执行任务.因此,要制作1000个作业并在5个线程中运行它们,我会执行以下操作:

I'm writing a load-testing application in Java, and have a thread pool that executes tasks against the server under test. So to make 1000 jobs and run them in 5 threads I do something like this:

    ExecutorService pool = Executors.newFixedThreadPool(5);
    List<Runnable> jobs = makeJobs(1000);
    for(Runnable job : jobs){
        pool.execute(job);
    }

但是,我认为这种方法无法很好地扩展,因为我必须提前制作所有作业"对象并将它们放在内存中,直到需要它们为止.

However I don't think this approach will scale very well, because I have to make all the 'job' objects ahead of time and have them sitting in memory until they are needed.

我正在寻找一种方法,让池中的线程在每次需要新作业时都进入某种'JobFactory'类,并让工厂根据请求构建Runnable,直到所需的作业数达到被运行.工厂可能会开始返回"null"以向线程发送信号,表明没有其他工作要做.

I'm looking for a way to have the threads in the pool go to some kind of 'JobFactory' class each time they need a new job, and for the factory to build Runnables on request until the required number of jobs have been run. The factory could maybe start returning 'null' to signal to the threads that there is no more work to do.

我可以手动编写类似的代码,但是这似乎是一个足够普通的用例,并且想知道在精美但复杂的'java.util.concurrent'软件包中是否可以代替使用? /p>

I could code something like this up by hand, but it seems like a common enough use-case and was wondering if there was anything in the wonderful but complex 'java.util.concurrent' package that I could use instead?

推荐答案

您可以使用AtomicInteger监视线程执行的数量,从而在线程池的执行线程中完成所有工作

You can do all the work in the executing threads of the thread pools using an AtomicInteger to monitor the number of runnables executed

 int numberOfParties = 5;
 AtomicInteger numberOfJobsToExecute = new AtomicInteger(1000);
 ExecutorService pool = Executors.newFixedThreadPool(numberOfParties );
 for(int i =0; i < numberOfParties; i++){
     pool.submit(new Runnable(){
        public void run(){
            while(numberOfJobsToExecute.decrementAndGet() >= 0){
                makeJobs(1).get(0).run();
            }
        }
     });
 }

您还可以将返回的期货存储在列表中,并在其上存储get()以等待完成(在其他机制中)

You can also store the returned Future's in a List and get() on them to await completion (among other mechanisms)

这篇关于如何懒惰地创建Java线程池使用的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆