I have some class. For example:
public class Data {
private String name;
public Data(String url) {
// There is download something from the Internet and set field "name".
}
public String getName() {
return name;
}
}
In some method I need to initialize array of objects Data.
ArrayList<Data> list = new ArrayList<Data>;
for(int i=0; i<max; i++) {
list.add(new Data("http://localhost/" + String.valueOf(i)));
}
But it is to long. I wanna do this:
final ArrayList<Data> list = new ArrayList<Data>;
for(int i=0; i<max; i++) {
final int tmp = i;
new Thread() {
public void run() {
list.add(new Data("http://localhost/" + String.valueOf(tmp)));
}
}.start();
}
But the main thread ends sooner than the others and variable list is empty. What should I do? Help pls 🙂
UP. That is not too fast to download some data from the Internet that’s why I’ve created several threads.
Instead of dealing with the low level details of the Thread API, you could use the java concurrent package, with an executor to handle the threads (I don’t know what ListArray is but if it is not thread safe you will have issues with the solution proposed some of the other answers: adding a join will not be sufficient).
For example, a simplified example would be:
Ideally, you whould add some error handling around
future.get(), as it will throw anExecutionExceptionif your task throws an exception, which I suppose could happen if the page is not availble for example.