根据Java中的条件动态添加执行程序

根据Java中的条件动态添加执行程序

本文介绍了根据Java中的条件动态添加执行程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果为StrTemp.equals(true),我需要以下代码(我在这里有2个线程):

If StrTemp.equals(true), I want code as below (I have 2 threads here):

ExecutorService executor = Executors.newFixedThreadPool(2);

Future<String> f1 = executor.submit(new Callable<String >() {
    public String  call() throws Exception {
        return dao.getS4PricingResponse(pricingRequestTemp);
    }
});
Future<String> f2 = executor.submit(new Callable<String>() {
    public String call() throws Exception {
        return dao.getS4ProductResponse(productRequestTemp);
    }
});

如果不是真的,我想创建三个线程.我将再添加一个f3=executor.submit.如何动态决定并提高效率?

If it's not true I want three threads to be created. I will add one more f3=executor.submit. How can I decide this dynamically and make it more efficient?

推荐答案

您正在混淆两个不属于一起的事物.

You are mixing up two things that don't belong together.

  • 执行程序服务及其任务:该服务不知道或不在乎有多少线程可以运行任务.换句话说:只需将您的工作项提交到其中即可.
  • 但是您必须预先修复"线程数量,简单的解决方案看起来会

像这样:

int numThreads = (whateverStrTemp.equals(somethingElse)) ? 2 : 3;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// now submit all the tasks you want to submit ...

关于评论:那是不容易做到的.方法调用在两个方面有所不同:被调用的方法和传递的参数!您可以将用于不同调用的lambda放入映射中,但是您可能需要另一个映射,该映射包含一个lambda来获取参数以传递给第一个lambda.从这种角度来看,我没有看到一种合理的方法来重构 this 代码.

Regarding the comment: that one isn't easily possible. The method calls differ in two aspects: the method that gets called and the parameter that gets passed! You could put lambdas for the different calls into a map, but you would probably need another map that holds a lambda that fetches the parameter to pass to the first lambda. From that point of view, I don't see a reasonable way to refactor just this code.

我会退后一步,看看您尝试解决的根本问题,并研究以不同方式进行设计的方法,以获得更好的解决方案.

I would step back, and look at the underlying problem you try to solve, and look into ways of designing that differently, to get to a better solution.

除此之外,您还可以将所有代码放入一个循环中,并将期货添加到List<Future<String>>中,而不用创建变量f1,f2,...(提示:每当您开始使用foo1,foo2, ...您应该立即停止并使用数组或列表.

Beyond that, you could put all that code into a single loop, and add the futures to a List<Future<String>> instead of creating variables f1, f2, ... (hint: whenever you start using names like foo1, foo2, ... you should stop immediately and use an array or list).

这篇关于根据Java中的条件动态添加执行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:51