C# 多线程学习(五)线程同步和冲突解决

首先先说一个线程不同步的例子吧,以下为售票员的模拟售票,多个售票员出售100张门票,代码如下:

using System;
using System.Text;
using System.Collections.Generic;
using System.Threading;

namespace threadTest
{
    class Program
    {

        class ThreadLock
        {
            private Thread thread_1;
            private Thread thread_2;

            private List<int> tickets;

             private object objLock = new object();//对象锁的对象
            public ThreadLock()
            {
                thread_1 = new Thread(Run);
                thread_1.Name = "Sailer_1";
                thread_2 = new Thread(Run);
                thread_2.Name = "Sailer_2";
            }
            public void Start()
            {
                tickets = new List<int>(100);
                for(int i = 1; i <= 100; i++)
                {
                    tickets.Add(i);
                }
                thread_1.Start();
                thread_2.Start();
            }
            public void Run()
            {
                while (tickets.Count > 0)
                {

                        int get = tickets[0];
                        Console.WriteLine("{0} sail a ticket ,ticket number :{1} ",
                            Thread.CurrentThread.Name, get.ToString());
                        tickets.RemoveAt(0);
                        Thread.Sleep(1);

                }
            }
        }
        static void Main()
        {
            ThreadLock TK = new ThreadLock();
            TK.Start();
            Console.ReadKey();
        }
    }
}

以上为一个模拟售票系统,两个线程对一个票箱进行操作,每次都取出最上层的票,然后输出,运行之后查看结果会发现在在同一张票上,两个线程都可能同时卖出,如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值