计费类具有与国家/地区明智计费相关的所有逻辑。它从数据库中获取结果,然后向用户计费。计费类实现Runnable。我想根据国家/地区参数并行执行计费,以便快速计费大量用户(500 万以上)。现在需要几个小时才能完成。
我正在尝试实现 ThreadPoolExecutor 来执行 Billing 类,但我很困惑如何实现?以下有什么区别或者我做错了什么?请推荐!!总共有 20 个国家,但我在这里只粘贴了 5 个。
//for 20 countries ThreadPoolExecutor (20,20,20.......)????
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10), new ThreadPoolExecutor.CallerRunsPolicy());
executor.execute(new Billing("UK"));
executor.execute(new Billing("USA"));
executor.execute(new Billing("Germany"));
executor.execute(new Billing("Spain"));
executor.execute(new Billing("Italy"));
或者
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10), new ThreadPoolExecutor.CallerRunsPolicy());
for(int i=0;i<5;i++) // for 20 countries i<20??
{
executor.execute(new Billing("UK"));
executor.execute(new Billing("USA"));
executor.execute(new Billing("Germany"));
executor.execute(new Billing("Spain"));
executor.execute(new Billing("Italy"));
}
while (! executor.isTerminated()) {
try{
executor.awaitTermination(100, TimeUnit.SECONDS);
}catch(InterruptedException iE)
{
iE.printStackTrace();
System.out.println("Executor Exception: "+ iE);
}
提前致谢!!
最佳答案
循环解决方案似乎不正确。无需多次执行相同的Runnable
。
您正在实例化 ThreadPoolExecutor
,并将 corePoolSize
和 maximumPoolSize
设置为 5
,这意味着执行程序将维护池中的线程数为 5
,即使它们处于空闲状态。它还表示池中的线程数不能超过 5
个。
完成此操作后,您最多可以并行运行 5
个线程来执行任务(Billing
对象)。
当您继续使用 execute
方法向 executor
提交 Billing
对象时,它们将被添加到由你。这里这个队列的大小是10
。在某些情况下,队列可能已经达到最大容量,无法接受更多任务,在这种情况下,任务会被拒绝并交给 ThreadPoolExecutor 中提供的
构造函数。它的工作是使用已实现的方法 RejectedExecutionHandler
。/rejectedExecution
处理被拒绝的任务。
如果您想查找是否有任何被拒绝的任务,您必须提供自己的RejectedExecutionHandler
,而不是使用默认的ThreadPoolExecutor.CallerRunsPolicy
。你可以用这样的东西来做到这一点:
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 5,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {
System.out.println("I got rejected: " + r);
if (!executor.isShutdown()) {
r.run();
}
}
});
关于java - ThreadPoolExecutor 运行应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15116818/