Java执行者:当任务完成时如何被通知,没有阻塞? [英] Java executors: how to be notified, without blocking, when a task completes?

查看:370
本文介绍了Java执行者:当任务完成时如何被通知,没有阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个拥有任务的队列,我需要提交给执行者服务。我希望他们一次处理一个。我可以想到的最简单的方法是:

Say I have a queue full of tasks which I need to submit to an executor service. I want them processed one at a time. The simplest way I can think of is to:


  1. 从队列中取出任务

  2. 提交

  3. 从队列中取另一个任务

  4. / li>
  1. Take a task from the queue
  2. Submit it to the executor
  3. Call .get on the returned Future and block until a result is available
  4. Take another task from the queue...

但是,我试图避免完全阻止。如果我有10,000个这样的队列,需要他们的任务一次处理一个,我将用尽堆栈空间,因为他们大多数将持有阻塞的线程。

However, I am trying to avoid blocking completely. If I have 10,000 such queues, which need their tasks processed one at a time, I'll run out of stack space because most of them will be holding on to blocked threads.

我想要的是提交任务,并提供任务完成时调用的回调。我将使用该回调通知作为标志发送下一个任务。 (functionjava和jetlang显然使用这样的非阻塞算法,但我不能理解他们的代码)

What I would like is to submit a task and provide a call-back which is called when the task is complete. I'll use that call-back notification as a flag to send the next task. (functionaljava and jetlang apparently use such non-blocking algorithms, but I can't understand their code)

我如何使用JDK的java.util.concurrent,short

How can I do that using JDK's java.util.concurrent, short of writing my own executor service?

(提供这些任务的队列本身可能会阻塞,但这是稍后需要解决的问题)

(the queue which feeds me these tasks may itself block, but that is an issue to be tackled later)

推荐答案

定义一个回调接口,以接收您要在完成通知中传递的任何参数。然后在任务结束时调用它。你甚至可以写一个Runnable任务的一般包装,并将它们提交到 ExecutorService

Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task. You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService.

class CallbackTask implements Runnable {

  private final Runnable task;

  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  public void run() {
    task.run();
    callback.complete();
  }

}

这篇关于Java执行者:当任务完成时如何被通知,没有阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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