Sunday, July 22, 2018

java - How to implement simple threading with a fixed number of worker threads



I'm looking for the simplest, most straightforward way to implement the following:




  • The main program instantiates worker

    threads to do a task.

  • Only n tasks can be running at once.

  • When n is reached, no more workers
    are started until the count of
    running threads drops back below n.


Answer



I think that Executors.newFixedThreadPool fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event.



  Collection tasks = new ArrayList();

YourTask yt1 = new YourTask();
...
tasks.add(yt1);
...
ExecutorService exec = Executors.newFixedThreadPool(5);
List> results = exec.invokeAll(tasks);


Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple execute(Runnable) method.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...