Before telling you what I have developed so far, I explain what I intend to do. I am experimenting with threads and create a method to process files (in total there are 3,000). With only one thread the process is a bit slow ... so I decided to try the following:
To increase the processing speed it occurred to me to distribute the files among 4 threads ( SwingWorkers ) to see how it goes.
I discovered a quite useful library for this purpose, which is Guava :
public static void parteUnArray(){
List<String> numeros = new ArrayList();
List<List<String>> th = new ArrayList<List<String>>();
int threads = 0;
numeros.add("Manzana");
numeros.add("Banana");
numeros.add("Pera");
numeros.add("Durazno");
numeros.add("Mora");
numeros.add("Canela");
numeros.add("Tomate");
numeros.add("Durian");
numeros.add("Duran");
numeros.add("Papa");
numeros.add("cabeza");
numeros.add("Mango");
System.out.println("Numeros de elementos: " + numeros.size());
if(numeros.size() >= 4)
threads = 4;
else
threads = numeros.size();
int i = 0;
for (List<String> partition : Lists.partition(numeros, numeros.size() / threads)) {
th.add(partition);
}
for(List<String> list: th){
i++;
for(String value : list){
System.out.println(i + " " + value);
}
}
}
With this library I can take a List and divide it according to the number of elements that I indicate, for example:
Here I point out to divide a 12-element arraylist into 4 parts, consisting of 3 elements each. With this library I could distribute the amount of tasks among the 4 threads ... but now my question comes:
Will there be any formula or some way of calculating the number of files to distribute among 4 threads?
As you can see, in this code that I shared, I only divided the number of elements among 4, which works well since 12 is divisible by 4 ... therefore, 4 groups of 3 elements will be created without problems. But as it is to be known, it will not always work ... for example, if you add 1 more element, the results would be completely unbalanced:
As you can see, a new group is created ... which is not what I want. I just want the elements to be distributed among 4 groups.