zoukankan      html  css  js  c++  java
  • C# 多线程程序隐患

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    //线程同步与多线程程序中的隐患
    namespace Multithreading_hazard
    {
        class Program
        {
            private static int stickets = 100;
            static void Main(string[] args)
            {
                Thread thread1 = new Thread(SaleTicketThread1);
                Thread thread2 = new Thread(SaleTicketThread2);
                thread1.Start();
                thread2.Start();
                Thread.Sleep(4000);
            }
    
            private static void SaleTicketThread1()
            {
                while (true)
                {
                    if (stickets>0)
                    {
                        Console.WriteLine("线程一出票{0}:", stickets--);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            private static void SaleTicketThread2()
            {
                while (true)
                {
                    if (stickets > 0)
                    {
                        Console.WriteLine("线程二出票{0}:", stickets--);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
    
    }

    因为两个线程访问了同一个静态变量stickets,线程出票的顺序发生了变化,将会引起数据出现错误.

    为了避免这种情况的发生,保证同一时间类只有一个线程访问共享资源;

    使用:线程同步:C# Monitor与线程同步

  • 相关阅读:
    C#博客记录二
    C#博客记录一
    label语句
    css选择器
    关于访问对象属性的小问题
    特殊符号unicode编码
    不换行
    正则表达式中的exec()方法
    正则表达式中两种定义方式中的反斜杠
    js删除对象数组
  • 原文地址:https://www.cnblogs.com/lbonet/p/7298603.html
Copyright © 2011-2022 走看看