龙空技术网

4-1综合练习-售票模拟-C#多线程编程基础

天道格律随笔 46

前言:

现在朋友们对“java多线程模拟售票”大致比较关注,我们都想要知道一些“java多线程模拟售票”的相关知识。那么小编也在网上网罗了一些有关“java多线程模拟售票””的相关内容,希望我们能喜欢,你们一起来了解一下吧!

以火车站售票系统为例,在代码中判断当前票数是否大于0,如果大于0,则执行把火车票出售给乘客的功能,但当两个线程同时访问这段代码时(只有1张票),第一个线程出票,与此同时第二个线程已经执行查询,并得出结果是0,于是执行负数操作。

完整示例代码:

运行结果

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;using System.Runtime.InteropServices;namespace SaleTicketsSys{    class Program    {        int num = 10;//设置当前总票数        void Ticket()        {            while (true)//设置无限循环            {                lock (this)//锁定代码块,以便线程同步                {                    if (num > 0)//判断当前票数是否大于0                    {                        Thread.Sleep(100);//使当前线程休眠100毫秒                        Console.WriteLine(Thread.CurrentThread.Name + "----票数" + num--);//票数减1                    }                    else                    {                         Console.WriteLine(Thread.CurrentThread.Name +"无票,请等待!");//每个线程都会在查一遍票数                        Thread.Sleep(1000);//使当前线程休眠1秒                        break;                    }                }            }        }        static void Main(string[] args)        {            Program p = new Program();//创建对象,以便调用对象方法            Thread tA = new Thread(new ThreadStart(p.Ticket));//分别实例化4个线程,并设置名称            tA.Name = "线程一";            Thread tB = new Thread(new ThreadStart(p.Ticket));            tB.Name = "线程二";            Thread tC = new Thread(new ThreadStart(p.Ticket));            tC.Name = "线程三";            Thread tD = new Thread(new ThreadStart(p.Ticket));            tD.Name = "线程四";            tA.Start(); //分别启动线程            tB.Start();            tC.Start();            tD.Start();            Console.ReadLine();        }    }}

标签: #java多线程模拟售票