代码是
class TestThread
{
int num = 50;
public void SellTicket()
{
for (int i=50;i >0;i-- )
{
if (num > 0)
{
Console.WriteLine(Thread.CurrentThread.Name + "卖出了第" + num + "张");
num--;
}
}
}
}
class Program
{
static void Main(string[] args)
{
TestThread a = new TestThread();//多线程模式。5
Thread mythr1 = new Thread(a.SellTicket);
mythr1.Name = "窗口一";
Thread mythr2 = new Thread(a.SellTicket);
mythr2.Name = "窗口二";
Thread mythr3 = new Thread(a.SellTicket);
mythr3.Name = "窗口三";
mythr1.Start();
mythr2.Start();
mythr3.Start();
Console.ReadKey();
}
}
运行之后出现了这么一些问题
1、卖出了第49张但是显示的是第50张。
2、买完最后一张之后居然还卖了两张。
这是线程同步问题
修改如下
using System;这样就正常了