java根据条件动态修改表,根据Java中的条件动态添加执行程序

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

ExecutorService executor = Executors.newFixedThreadPool(2);

Future f1 = executor.submit(new Callable() {

public String call() throws Exception {

return dao.getS4PricingResponse(pricingRequestTemp);

}

});

Future f2 = executor.submit(new Callable() {

public String call() throws Exception {

return dao.getS4ProductResponse(productRequestTemp);

}

});

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.

the executor service and its tasks: that service doesn't know or care about how many threads will be there to run tasks. In other words: just submit your work items into it.

but you have to "fix" the number of threads upfront, and the simple solution would look

like this:

int numThreads = (whateverStrTemp.equals(somethingElse)) ? 2 : 3;

ExecutorService executor = Executors.newFixedThreadPool(numThreads);

// now submit all the tasks you want to submit ...

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.

Beyond that, you could put all that code into a single loop, and add the futures to a List> 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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值