最好的方法等待任务完成之前添加新的到线程池中的Java? [英] Best way to wait on tasks to complete before adding new ones to threadpool in Java?

查看:236
本文介绍了最好的方法等待任务完成之前添加新的到线程池中的Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用类似ThreadPoolExecutor的东西来管理在可用线程上运行一堆任务。这些任务都是相同的类型,但处理不同的帐户。这些帐户的新任务可以定期添加,我希望它们检查并且不允许新任务开始,直到同一帐户的旧任务已经完成。这是最好的方法是什么?



示例




  1. (通过ThreadPoolExecutor.execute())启动帐户234(通过ThreadPoolExecutor.execute())


  2. / p>

  3. 帐户234的新任务已创建,但未添加执行,因为第一个234任务未完成

  4. 帐户238的新任务开始(通过ThreadPoolExecutor) .execute()),因为当前没有该帐户正在运行


只需要检查一个wait / sleep()为Runnable中的一些检查变量的234的第一个任务完成?或者有更好的解决方案吗?

解决方案

我面临同样的问题。我的解决方案是使用一个HashSet。

  private static HashSet< Integer> runningTasks = new HashSet(); 

public void run(){
boolean isAlreadyRunning = false;
synchronized(runningTasks){
if(runningTasks.contains(this.accountId)){
isAlreadyRunning = true;
} else {
runningTasks.add(this.accountId);
}
}
if(isAlreadyRunning){
//调度此任务稍后在此运行
//我所做的是将此任务重新插入任务队列5秒后
return;
}
//这里做你的东西

synchronized(runningTasks){
runningTasks.remove(this.accountId);
}
}


I want to use something like a ThreadPoolExecutor to manage running a bunch of tasks on available threads. These tasks are all of the same type but deal with different accounts. New tasks for these accounts can be added at regular intervals and I want it to check and not allow the new tasks to start until the old tasks for the same account have already completed. What's the best way to do this?

EXAMPLE

  1. Task for account "234" is started (via ThreadPoolExecutor.execute())

  2. Task for account "238" is started (via ThreadPoolExecutor.execute())

  3. New Task for account "234" created but not added to execute because first "234" task not complete (best way to check this?)

  4. Task for account "238" completes

  5. New Task for account "238" starts (via ThreadPoolExecutor.execute()) because none currently running for that account

What's the best way to do this? Simply have it check with a wait/sleep() for some check variable in the Runnable for "234"'s first task to finish? Or is there a better solution?

解决方案

I faced the same issue. My solution was to use a HashSet.

private static HashSet<Integer> runningTasks = new HashSet();

public void run(){
  boolean isAlreadyRunning = false;
  synchronized (runningTasks) {
    if (runningTasks.contains(this.accountId)) {
      isAlreadyRunning = true;
    } else {
      runningTasks.add(this.accountId);
    }
  }
  if(isAlreadyRunning){
    //schedule this task to run later here
    //what I did was to reinsert this task to the task queue 5 seconds later
    return;
  }
  //do your stuffs here

  synchronized (runningTasks) {
    runningTasks.remove(this.accountId);
  }
}

这篇关于最好的方法等待任务完成之前添加新的到线程池中的Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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