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与线程同步