java multithreaded programming job code

Please divide it into 6 threads and calculate the sum of the values ​​from m to n (take 1 to 100000000 as an example). The difference between the number of numbers calculated by each thread is not more than 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();
			}
		}
	}
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/DwenKing/article/details/109333503