Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 741
shsteimer Avatar asked Sep 24 '08 03:09

shsteimer


People also ask

What are worker threads?

Worker thread is a continuous parallel thread that runs and accepts messages until the time it is explicitly closed or terminated. Messages to a worker thread can be sent from the parent thread or its child worker threads. Through out this document, parent thread is referred as thread where a worker thread is spawned.

How many threads does an executor pool have?

The function then creates ThreadPoolExecutor with the 5 threads in the pool.


2 Answers

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<YourTask> tasks = new ArrayList<YourTask>();   YourTask yt1 = new YourTask();   ...   tasks.add(yt1);   ...   ExecutorService exec = Executors.newFixedThreadPool(5);   List<Future<YourResultType>> 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.

like image 150
erickson Avatar answered Sep 25 '22 15:09

erickson


/* Get an executor service that will run a maximum of 5 threads at a time: */ ExecutorService exec = Executors.newFixedThreadPool(5); /* For all the 100 tasks to be done altogether... */ for (int i = 0; i < 100; i++) {     /* ...execute the task to run concurrently as a runnable: */     exec.execute(new Runnable() {         public void run() {             /* do the work to be done in its own thread */             System.out.println("Running in: " + Thread.currentThread());         }     }); } /* Tell the executor that after these 100 steps above, we will be done: */ exec.shutdown(); try {     /* The tasks are now running concurrently. We wait until all work is done,       * with a timeout of 50 seconds: */     boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);     /* If the execution timed out, false is returned: */     System.out.println("All done: " + b); } catch (InterruptedException e) { e.printStackTrace(); } 
like image 27
Fabian Steeg Avatar answered Sep 23 '22 15:09

Fabian Steeg