I have a arraylist which consists of 5000 IP Addresses. For each IP Address, I want to execute a SNMPGet request and a FTPDownload command. I want to implement it in a fashion,
Executor Framework will be best suit for your solution. I have created one example here. You can increase the number of threads as per your requirement.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class SomeRunnable implements Runnable {
int threadNo = -1 ;
List list = new ArrayList();
public SomeRunnable(List list, int threadNo ) {
this.list.addAll(list);
this.threadNo =threadNo;
}
@Override
public void run() {
for (String element : list) {
System.out.println("By Thread:" + threadNo+", Processed Element:" +element);
}
}
}
public class ExecutorDemo {
public static void main(String[] args) {
List list = new ArrayList();
for (int i = 0; i < 100; i++) {
list.add("Elem:"+i);
}
// Divide list
int divideIndex = list.size()/2;
//Create objects of Runnable
SomeRunnable obj1 = new SomeRunnable(list.subList(0, divideIndex),1);
SomeRunnable obj2 = new SomeRunnable(list.subList(divideIndex,list.size()),2);
//Create fixed Thread pool, here pool of 2 thread will created
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(obj1);
pool.execute(obj2);
pool.shutdown();
}
}