package com.gmail.vhrushyn;
public class MySummArray implements Runnable {
private int[] intArr;
private int[] summ;
private int from;
private int to;
public MySummArray() {
super();
// TODO Auto-generated constructor stub
}
public MySummArray(int[] intArr, int[] summ, int from, int to) {
super();
this.intArr = intArr;
this.summ = summ;
this.from = from;
this.to = to;
}
@Override
public void run() {
mySum();
}
private void mySum () {
int sum = 0;
try {
for (int i = from; i < to; i++) {
sum += intArr[i];
}
} catch (ArrayIndexOutOfBoundsException e) {
; // skip out of bounds
}
summ[Integer.parseInt(Thread.currentThread().getName())] = sum;
// System.out.println("thread sum = "+sum);
}
}
package com.gmail.vhrushyn;
import java.util.Date;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] intArr = new int[20000000];
Random rd = new Random();
for (int i = 0; i < intArr.length; i++) {
intArr[i] = rd.nextInt(10);
}
Date startThread = new Date();
int qC = (Runtime.getRuntime().availableProcessors()) * 2;
int[] summ = new int[qC];
int from = 0;
int to = (intArr.length / qC) + 1;
int c = 0;
for (int i = 0; i < qC; i++) {
Thread t = new Thread(new MySummArray(intArr, summ, from, to), "" + i + "");
t.start();
from = to;
to += (intArr.length / qC) + 1;
c = c + 1;
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int sum = 0;
for (int i : summ)
sum += i;
Date stopThread = new Date();
long speedThread = stopThread.getTime() - startThread.getTime();
System.out.println("time in multy-thread way = " + speedThread+" millis, " + " sum = " + sum);
Date startRegular = new Date();
int sumTwo = 0;
for (int i = 0; i < intArr.length; i++) {
sumTwo += intArr[i];
}
Date stopRegular = new Date();
long speedRegular = stopRegular.getTime() - startRegular.getTime();
System.out.println("time in regular way = " + speedRegular+" millis, " + " sum = " + sumTwo);
}
}