Divídalo en 6 subprocesos y calcule la suma de los valores de m an (tome de 1 a 100000000 como ejemplo). La diferencia entre el número de números calculados por cada hilo no es más de 1.
import java.util.Vector;
public class CountSum {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Vector<Thread> threadVector =new Vector<Thread>();
int from,to,num;
from=1;
to=10000000;
num=6;
int interval=(to-from+1)/num;
int thread_bg,thread_ed;
thread_bg=1;
for(int i=0;i<6;i++) {
if(i==0)thread_ed=thread_bg+interval-1;
else if(thread_bg+interval>to)
thread_ed=to;
else
thread_ed=thread_bg+interval;
Thread childThread=new Thread(new SumThread(thread_bg,thread_ed));
threadVector.add(childThread);
childThread.start();
thread_bg=thread_ed+1;
}
for(Thread t:threadVector) {
t.join();
}
System.out.println(SumThread.sum);
}
}
class SumThread implements Runnable{
private int bg,ed;
public static long sum=0;
public static Integer lock = 1;
public SumThread(int b,int e) {
this.bg=b;
this.ed=e;
}
public void run() {
synchronized(lock) {
System.out.println("from "+bg+" to "+ed+",total:"+(ed-bg+1));
try {
for(int i=bg;i<=ed;i++) {
sum+=i;
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
resultado: