Reputation: 27
I'm learning to use threads in java, since I want to speed up a task to reduce time. I try to see how long it takes to finish the threads but since I don't know how to use join in this case:
public class MyThread1 extends Thread {
int inicio;
int fin;
public MyThread1(int _inicio, int _fin) {
this.inicio = _inicio;
this.fin = _fin;
}
@Override
public void run() {
String pass;
for(int i = inicio; i < fin; i++){
pass = Integer.toString(i);
System.out.println(pass);
}
}
}
public static void main(String arg[]) throws UnknownHostException {
long previousTime;
previousTime = System.currentTimeMillis();
int threads = 10; // Number of threads
for (int i = 0; i < threads; i++) {
MyThread1 object = new MyThread1(0,10);
object.start();
}
long currentTime = System.currentTimeMillis();
double elapsedTime = (currentTime - previousTime) / 1000.0;
System.out.println("Time in seconds : " + String.valueOf(elapsedTime));
}
Upvotes: 0
Views: 152
Reputation: 44834
Add MyThread1 object
to an array that is declared before the loop. After the loop, have another loop which will join on all objects.
for (int i = 0; i < threads; i++) {
MyThread1 object = new MyThread1(0,10);
arr[i] = object;
object.start();
}
for (int i = 0; i < threads; i++) {
arr[i].join();
}
Upvotes: 1