ScheduledExecutorService - 忽略已经运行的 runnable [英] ScheduledExecutorService - Ignore already running runnable

查看:62
本文介绍了ScheduledExecutorService - 忽略已经运行的 runnable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用预定的执行程序服务

I'm using a scheduled executor service

private ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(1);

以固定速率运行可运行对象

running a runnable at fixed rate

pool.scheduleAtFixedRate(new CoolRunnable(), 10, 10, TimeUnit.MILLISECONDS);

这个线程池等待前一个执行完成,但我希望它每 10 毫秒运行一次 runnable,无论前一个是否完成.

This thread pool waits that the previous execution finishes, but i'd like it to run the runnable every 10 milliseconds no matter whether the previous is done or not.

我该怎么做?

修复了用连接池替换 MySQL 连接的问题.正常的连接方法是同步的,这就是为什么 runnable 必须互相等待.

Fixed the problem replacing the MySQL connection with a connection pool. The normal connection methods are synchronized, that's why the runnables had to wait for each other.

推荐答案

为此,您需要每 10 秒向 ExecutorService 提交一个任务.这个 ExecutorService 将负责运行任务:

To do that, you need to submit a task to an ExecutorService every 10s. This ExecutorService is the one that will take care of running the tasks:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ExecutorService workers = Executors.newCachedThreadPool();

scheduler.scheduleAtFixedRate(new Runnable {
    @Override
    public void run() {
        workers.submit(new CoolRunnable());
    }
}, 10, TimeUnit.SECONDS);

如果旧线程仍在工作,则使用 cachedThreadPool 将创建新线程.这样做时要小心:如果任务需要更长的时间来运行,每 10 秒添加一个新任务可能会创建大量并发线程.

Using a cachedThreadPool will create new threads if older ones are still working. Careful in doing so: adding a new task every 10 seconds might create a lot of concurrent threads if the tasks take a lot longer to run.

这篇关于ScheduledExecutorService - 忽略已经运行的 runnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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