I have a program which has to process a list with many jobs. To speed up the whole things, I would like to implement Threads.
I think about something like this:
Main-Class
// I have a joblist with 100 entries
int iAmountThreads = 5;
for(Job oJob : joblist)
{
//only execute 5 Jobs at the same time
if(Thread.activeCount() < iAmountThreads)
{
Runnable threadJob = new JobRunnable(oJob);
Thread myThread = new Thread(threadJob);
myThread.start();
}
}
//wait here until all jobs from the joblist are finished
Runnable Class Implementing Runnable
public class JobRunnable implements Runnable
{
private Job oJob;
public JobRunnable(Job _oJob)
{
oJob = _oJob;
}
public void run()
{
//processing of the job
}
}
I'm looking for a way to run 5 Jobs at the same time until the whole list is processed. When one Job is finished -> the next Thread shall start.
Thanks for any help!
Use a fixed thread pool, via the executor API:
Executor executor = Executors.newFixedThreadPool(5);
// all jobs are submitted sequentially, but only 5 jobs execute concurrently at a time
for(Runnable job : jobs)
{
executor.execute(job);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With