Reputation: 2424
Im trying to take a for loop like this:
List<Object> users;
public void doSomething() {
for (Object o : users) {
// split up the for loop
// and handle chunks of the iteration
// across multiple threads
o.doThis();
o.doThat();
}
}
And divide the iteration for(Object o: users){
into multiple threads. How can I do this with Java while not causing concurrent modifications. My goal is to scale this like a thread pool, so the more objects in List<Object> users;
means more threads handling a chunk of the iteration.
I am new to multithreading and am not sure what java utils could help accomplish this.
Upvotes: 2
Views: 587
Reputation: 2922
You can use java.util.concurrent.Executors class which would assist you in executing multiple thread concurrently.
Have written a small method, which can assist your understanding.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
Upvotes: 1
Reputation: 3704
If you are using java 8, streams would be the simplest way
users.parallelStream()
.forEach(u -> { u.doThis(); u.doThat(); } );
You could also implement a runnable interface, and create a ThreadExecutor. This would be much more code than the above example.
Upvotes: 2