Process tasks from a list using Java streams
I have a program that needs to process a list with many tasks. To speed things up, I would like to implement Threads.
I am thinking of 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 Implementation Runnable
public class JobRunnable implements Runnable
{
private Job oJob;
public JobRunnable(Job _oJob)
{
oJob = _oJob;
}
public void run()
{
//processing of the job
}
}
I am looking for a way to run 5 Jobs at the same time until the entire list is processed. When one job is complete → the next thread will start.
Thanks for any help!
+3
source to share
3 answers
The easiest way is to use Java 8 parallel streams. Simple implementation:
List<JobRunnable> tasks = ...;
tasks.parallelStream()
forEach(JobRunnable::run);
This can be changed and you don't need to use Runnable
; you can use any method from any class. You have to be careful with thread safety, but don't share state between objects in the list.
+1
source to share