Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process Jobs from a list with Java Threads

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!

like image 769
John Smithv1 Avatar asked Jul 12 '26 03:07

John Smithv1


1 Answers

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);
}
like image 181
Eng.Fouad Avatar answered Jul 14 '26 16:07

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!