题目:请分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求每个线程计算的数字量之差不超过1.
/**
* 请分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求每个线程计算的数字量之差不超过1.
* @author MSS
*
*/
public class Accumulation {
public static void main(String[] args) throws InterruptedException {
int m=1;
int n=100000000;
int k=n-m+1;
int quotient=k/6; //商
int remainder=k%6; //余数
long sum=0;
Sum totalSum=new Sum(sum,m,n);
for(int i=1;i<n+1;i++) {
sum=sum+i;
}
System.out.println("商:"+quotient+" 余数:"+remainder+" 参考结果:"+sum);
Thread[] thread=new Thread[6];
for(int i=0;i<6;i++) {
if(remainder>0) {
thread[i]=new Thread(new AccThread(totalSum,quotient+1)); //比其他线程多算1次的线程数量为余数值
remainder--;
}else {
thread[i]=new Thread(new AccThread(totalSum,quotient));
}
thread[i].setName("累加器"+i);
thread[i].start();
}
while(totalSum.flag) {
Thread.sleep(1000);
}
System.out.println(m+"到"+n+"的总和为:"+totalSum.getSum());
}
}
class AccThread implements Runnable{
private Sum sum;
private int count;
public AccThread(Sum sum,int count) {
this.sum=sum;
this.count=count;
}
@Override
public synchronized void run() {
sum.add(count); //count为每个线程的累加次数
System.out.println(Thread.currentThread().getName()+" partSum:"+sum.getSum()+" a:"+sum.getA());
}
}
class Sum{
public volatile boolean flag=true;
private long sum=0;
private int a=0;
private int n=0;
public Sum(long sum, int a,int n) {
super();
this.sum = sum;
this.a = a;
this.n=n;
}
public long getSum() {
return sum;
}
public int getA() {
return a;
}
public synchronized void add(int count) { //同步函数
for(int i=0;i<count;i++) {
sum=sum+a; //累加
a++;
if(a==n+1) {
flag=false;
}
}
}
}