ScheduledExecutorService - Ignore already running runnable

谁说胖子不能爱 提交于 2019-12-25 15:40:10

问题


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);

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.

How can I do that?

EDIT: 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.


回答1:


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);

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.



来源:https://stackoverflow.com/questions/32188597/scheduledexecutorservice-ignore-already-running-runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!