Friday, May 21, 2021

Multi thread and Concurrency - Simple MultiExecutor

 Very simple code block of MultiExecutor class


package thread.example;

import java.util.ArrayList;
import java.util.List;

/**
* <p>The client of this class will create a list of <code>Runnable</code> tasks and
 provide that list into <code>MultiExecutor</code>'s constructor.</p>
* <p>When the client runs the&nbsp; <code>executeAll()</code>,&nbsp;
the <code>MultiExecutor</code>,&nbsp; will execute all the given tasks.</p>
* <p>To take full advantage of our multicore CPU, we would like the
<code>MultiExecutor</code> to execute all the tasks in parallel, 
by passing each task to a different thread.</p>
*/
public class MultiExecutor {

// Add any necessary member variables here
private final List<Runnable> tasks;

/*
* @param tasks to executed concurrently
*/
public MultiExecutor(List<Runnable> tasks) {
// Complete your code here
this.tasks = tasks;
}

/**
* Starts and executes all the tasks concurrently
*/
public void executeAll() {
// complete your code here
// create list of threads
List<Thread> threads = new ArrayList<>(tasks.size());
// for each task create a thread and add to thread list.
for (Runnable task : tasks) {
Thread thread = new Thread(task);
threads.add(thread);
}

// start each thread
for (Thread thread : threads) {
thread.start();
}
}
}

No comments:

Post a Comment