# 线程同步时，越界的问题。计算1-100平方,结果是1-103的平方，多了3个。

0

```private static void RunThread()
{
CountDemo demo = new CountDemo();
start.IsBackground = true;
start.Name = "线程一";
start.Start();
start2.IsBackground = true;
start2.Name = "线程二";
start2.Start();
start3.IsBackground = true;
start3.Name = "线程三";
start3.Start();
start4.IsBackground = true;
start4.Name = "线程四";
start4.Start();
start5.IsBackground = true;
start5.Name = "线程五";
start5.Start();
}

public class CountDemo
{
public static object str=new object ();
public CountDemo()
{

}
public static int index{ get; set; }
public void Countsqurt()
{
while (index<100)
{

lock (str)
{
int num =index++;
double res = Math.Pow(num, 2);
Console.WriteLine("{0}的平方是{1}", num, res);
}
}
}
}```
、朔风 | 初学一级 | 园豆：151

0

public  void Countsqurt()
{

while (true)
{

lock (str)
{
if (++index > 100)
{
return; //方法结束了，方法对应的线程自然也终止了。
}

double res = Math.Pow(index, 2);
Console.WriteLine("{0}的平方是{1}", index, res);
}

}
}

、朔风 | 园豆：151 (初学一级) | 2016-01-12 15:38

@、朔风: 懂了就好！有问题欢迎再发博问～

0

0

```            public void Countsqurt()
{

lock (str)
{
while (index <= 100)
{
int num = index++;
double res = Math.Pow(num, 2);
Console.WriteLine("{0}的平方是{1}", num, res);

}
}
}```

您需要登录以后才能回答，未注册用户请先注册