ThreadPool 之于 Executor 就像 Polling 之于?

发布于 2024-07-26 02:07:16 字数 232 浏览 9 评论 0原文

Java 的 Executor(据我理解)是 ThreadPool 概念的抽象 - 可以接受并执行(执行)任务的东西。

我正在寻找轮询概念的类似例外。 我需要不断地从特定队列(未实现 BlockingQueue)中轮询(出队)项目,执行它们并睡眠,然后重复所有这些直到关闭。

是否有现成的抽象或者我应该自己写一些东西?

(欢迎提出更好的标题)

Java's Executor is (as far as I understand it) an abstraction over the ThreadPool concept - something that can accept and carry out (execute) tasks.

I'm looking for a similar exception for the Polling concept. I need to continuously poll (dequeue) items out of a specific Queue (which does not implement BlockingQueue), execute them and sleep, and repeat all this until shutdown.

Is there a ready-made abstraction or should I write something on my own?

(Suggestions of a better title are welcome)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不打扰别人 2024-08-02 02:07:16

投票很简单:

Thread t = new Thread(new Runnable() {
    public void run() {
        try {
            while (!t.isInterrupted()) {
               Object item;
               while ((item = queue.take()) == null) {//does not block
                   synchronized (lock) { lock.wait(1000L) } //spin on a lock
               }
               //item is not null
               handle(item);
            }
        } catch (InterruptedException e) { }
    }
});
t.start();

也许您需要重新表述您的问题,因为我不太确定您到底想做什么?

Polling is easy:

Thread t = new Thread(new Runnable() {
    public void run() {
        try {
            while (!t.isInterrupted()) {
               Object item;
               while ((item = queue.take()) == null) {//does not block
                   synchronized (lock) { lock.wait(1000L) } //spin on a lock
               }
               //item is not null
               handle(item);
            }
        } catch (InterruptedException e) { }
    }
});
t.start();

Perhaps you need to rephrase your question as I'm not quite sure exactly what it is you are trying to do?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文