Sunday, 1 September 2013

Parallel for loops in java

Parallel for loops in java

When I use one loop from one to million it takes less time then when i use
multiple threads dividing the loop counter in threads. my code is
class Looper implements Runnable {
private int start;
private int end;
private long time;
private long time1;
public Looper(int start, int end,long time1){
this.start = start;
this.end = end;
time=System.nanoTime();
this.time1=time1;
}
@Override
public void run() {
for(int i=start; i<end; i++){
System.out.println(" index : " + i) ;
}
time=System.nanoTime()-time;
System.out.println("Time taken by this thread is :"+time/100000 + "
and by loop was"+ time1/100000 );
}
}
public class DevideWork {
public static void main(String[] args){
long time=System.nanoTime();
for(int i=0;i<1000000;i++){
System.out.println(" index :"+i);
}
time=System.nanoTime()-time;
Thread looper1 = new Thread(new Looper(1,250000,time));
Thread looper2 = new Thread (new Looper(250001,500000,time));
Thread looper3 = new Thread(new Looper(500001,750000,time));
Thread looper4 = new Thread (new Looper(750001,1000000,time));
looper1.start();
looper2.start();
looper3.start();
looper4.start();
// System.out.println("Time taken is:"+ (System.currentTimeMillis()-time));
}
}

No comments:

Post a Comment