MOOC华东师范大学 Java核心技术(进阶)第五章作业 多线程实现累加

题目:请分成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;   
		   }
		} 
	}	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值