Search code examples
javamultithreadingrunnablescheduledexecutorservice

How to use Multiple runnable interfaces in single thread?


I am developing a java application which computes various mathematical functions. Here is the scenario, I have M runnable tasks (each for computing various problems, like one solves quadratic eqns, other solves exponential functions, something like that). These M runnables has to be executed for every N mins. These runnables can be executed sequentially not necessarily in parallel manner. I am not allowed to create more than one thread.

I can use ScheduledExecutorService for running the tasks periodically. As per Javadoc, Only one runnable can be used with ScheduledExecutorService. There are methods like invokeAll(...), which allows us to provide Collection of runnable, but these doesnt provide scheduling option.

On browsing through internet I found, using Thread.sleep() is not a good way to develop an application.

Any suggestions??


Solution

  • You can create ExecutorService that contains only one thread to run your jobs:

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    

    When you submit several jobs to this service using invokeAll method it will run them sequentially using single Thread instance.

    If you want to use ScheduledExecutorService to run your jobs every N minutes you can switch to

    ScheduledExecutorService scheduledExecutorService = 
        Executors.newSingleThreadScheduledExecutor();
    

    that will provide you with additional methods to better control your jobs.

    As you can see invokeAll method is derived from ExecutorService, so it does not provide you scheduling options. Still this is just a shortcut and you can schedule multiple Runnable instances using regular loop:

    for (Runnable job : allJobs) {
        scheduledExecutorService.scheduleAtFixedRate(job, 0L, N, TimeUnit.MINUTES);
    }