向 executorservice 请求新任务的线程

Thread to ask for new tasks from executorservice

我目前有收集任务的主要方法。收集任务后,将使用固定线程池大小调用 ExecutorService。任务迭代提交给执行器

但我需要刷新任务,如果有任何新任务可用,我会将其添加到执行程序中。但是,如果其中一个线程空闲而没有从队列中分配任何任务,我希望该线程手动通知我的主线程刷新事件并提交给执行程序,甚至在我端进行手动刷新之前。我怎样才能做到这一点。谢谢

示例代码

public class Sample{
   Map<String, List<Integer>> tasks;
   ThreadPoolExecutor executor;

   public static void main(String[] args) {
     executor = Executors.newFixedThreadPool(2);
     tasks = Collections.synchronizedMap(new HashMap<String, List<Integer>>());
     tasks =  Tasks.refresh(); //This will get me a new set of data to be processed
     invokeexecutor();
   }
   public void invokeexecutor(){
      for(String key: tasks.keyset())
      {
       executor.submit(new TaskRunnable(tasks.get(key));
      }
      tasks.clear(); //Remove the allocated tasks from the collection
   }
}

public class TaskRunnable implements Runnable{
   public void run(){
        //Do some logic
   }
}

在这种情况下,我希望任务中的数据在 10 秒后连续刷新,或者如果任何执行程序线程空闲,则必须进行此刷新,并且必须将新的可运行对象分配给该线程。

But if one of the thread is free without any tasks to be allocated from the queue, I want that thread to manually notify my main thread to refresh the events and submit to executor even before the manual refresh is happening from my end. How can i achieve this.

您可以通过多种方式轻松实现这一目标。一种方法是自己创建“ThreadPoolExecutor”。

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
                                             new LinkedBlockingQueue<Runnable>());

然后有一个轮询线程监视 ThreadPoolExecutor class 以确定是否有任何空闲线程。类似于:

 while (!Thread.currentThread().isInterrupted()) {
     // sleep a bit
     Thread.sleep(1000);
     if (executor.getActiveCount() < 2) {
        // add tasks here
     }
 }

然而,轮询线程有点恶心。另一个更简单的想法是使用固定大小的任务队列,然后始终尝试将任务添加到列表中。如果队列已满,这将阻塞。类似于:

// create a limited blocking queue
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
                                             new LinkedBlockingQueue<Runnable>(10));
 while (!Thread.currentThread().isInterrupted()) {
     // add tasks here which will block if too many in the queue
 }

您可以尝试覆盖 ThreadPoolExecutor 中的 afterExecute 方法。当池中的线程执行任务时调用它。

class MyThreadPoolExecutor extends ThreadPoolExecutor {
    public MyThreadPoolExecutor {
        super(/*Call one of TheadPoolExecutor constructors*/)
    }

    protected afterExecute(Runnable r, Throwable t) {
        // Notify main thread here
    }
}