c#多线程实例出现问题(买票实例)

代码是
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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;

namespace ConsoleApplication1
{
    class TestThread
    {
        //volatile将禁止将num优化到各个线程的存储区中
        volatile int num = 50;
        //用于lock
        object sync = new object();
        public void SellTicket()
        {
            for (int i = 50; i > 0; i--)
            {
                lock (sync)
                {
                    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();
        }
   
    }
}

这样就正常了

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答