package javaapplication31;
public class JavaApplication31 {
public static void main(String[] args) {
QiuheThread q[]=new QiuheThread[5];
for(int i=0;i<5;i++)
{
q[i]=new QiuheThread(i);
q[i].start();
}
int he=q[0].sum+q[1].sum+q[2].sum+q[3].sum+q[4].sum;
System.out.print("1-100求和为:"+he);
}
}
class QiuheThread extends Thread
{
int index;
int sum;
public QiuheThread(int nindex)
{
index=nindex;
}
public void run()
{
sum=0;
int i;
for(i=0;i<20;i++)
{
sum+=index*20+i+1;
}
System.out.println(sum);
add(sum);
}
public synchronized void add(int num)
{
sum+=num;
}
}
想用五个线程求1-100的和,第一个线程求1-20以此类推,给sum加锁之后单个线程求和正确,总体之不正确是怎么回事?求指点🙏