示例1:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ea2b0307a195610c8a9d753acddb6aee.png)
package work4;
public class Work4 {
public static void main(String[] args){
Integer toMax=100000000;
int threads=6;
MultisSum[] sumThread=new MultisSum[threads];
for (int i = 0; i < threads; i++) {
int fromInt=toMax*i/threads+1;
int toInt=toMax*(i+1)/threads;
sumThread[i]=new MultisSum(fromInt,toInt);
sumThread[i].start();
}
while (true){
Boolean sumOk=true;
for (int i = 0; i <threads ; i++) {
sumOk= sumThread[i].getSumOk();
}
if (sumOk) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long sum=0;
for (int i = 0; i < threads; i++) {
sum+= sumThread[i].getSum();
}
System.out.println("1到"+toMax+"的总和为:" + sum);
}
}
class MultisSum extends Thread {
private Integer start;
private Integer end;
private long sum=0;
private Boolean sumOk=false;
public Boolean getSumOk() {
return sumOk;
}
public long getSum() {
return sum;
}
public MultisSum(Integer start, Integer end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
sum+=i;
}
System.out.println(Thread.currentThread().getName()+":计算的数子量为:"+(end-start)+";"+start + "--" + end + "相加等于:" + sum);
sumOk=true;
}
}
示例2:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6ae34f5ce15c4a3d0f0f1cdceb37d6b8.png)
package work4;
public class Test {
public static void main(String[] args) {
int m = 1;
int n =100000000;
System.out.println("caculate sum: "+m+"~"+n);
if(m>n) {
int i =m;
m = n;
n = i;
}
int size = n-m+1;
int partSize = size/6;
int mod = size%6;
SumNumThread t = new SumNumThread();
for(int i =0;i<6;i++) {
t.partSizes[i]=partSize;
if(mod>0) {
t.partSizes[i]++;
mod--;
}
}
t.startNums[0]=m;
for(int i =1;i<6;i++) {
t.startNums[i]=t.startNums[i-1]+t.partSizes[i-1];
}
new Thread(t, "Thread-0").start();
new Thread(t, "Thread-1").start();
new Thread(t, "Thread-2").start();
new Thread(t, "Thread-3").start();
new Thread(t, "Thread-4").start();
new Thread(t, "Thread-5").start();
while (true) {
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (t.endFlag == 6) {
break;
}
}
System.out.print("total="+t.sum);
}
}
class SumNumThread implements Runnable {
public volatile long sum = 0;
public volatile int seq = 0;
public volatile int endFlag = 0;
public volatile int[] partSizes= new int[6];
public volatile int[] startNums= new int[6];
@Override
public void run() {
int seq = getSeq();
int tempNum = startNums[seq];
int partSize = partSizes[seq];
long partSum = 0;
int i = 0;
for(i = 0;i<partSize;i++) {
partSum+=tempNum;
tempNum++;
}
sum(partSum);
setEndFlag();
System.out.println("Thread-"+seq+": "+startNums[seq]+"~"+(tempNum-1)+"("+i+") sum="+partSum);
}
public synchronized int getSeq() {
return seq++;
}
public synchronized void setEndFlag() {
this.endFlag++;
}
public synchronized void sum(long partSum) {
this.sum+=partSum;
}}