多线程1~100 0000的加法分开计算100个线程每个线程计算10000计算完合并结果线程同步问题(争抢)线程唤醒

2025年03月01日 08:19
有1个网友回答
网友(1):

public class Test {
public static double sumAll = 0;
public static void main(String[] args) throws Exception {
for(int i=0;i<100;i++) {
myThread2 thread = new myThread2(i);
thread.start();
}
}
}

class myThread2 extends Thread {
double startNum;

public myThread2(int i) {
this.startNum = i;
}

@Override
public void run() {
double sum =0;
for(double i=startNum*10000+1;i<=startNum*10000+10001;i++) {
sum+=i;
}
synchronized (Test.class) {
System.out.print("sum="+sum);
Test.sumAll+=sum;
System.out.println(" 我是第"+(startNum+1)+"个线程累计的结果"+Test.sumAll);
}
}
}

简单的实现了一下,因为计算结果溢出了,这里先简单的用double处理了,还有感觉并不需要用到线程唤醒