java多线程编程作业代码

请分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求每个线程计算的数字量之差不超过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();
			}
		}
	}
}

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/DwenKing/article/details/109333503