多线程
Posted 刘奇云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程相关的知识,希望对你有一定的参考价值。
线程安全问题都是由全局变量及静态变量引起的。
class Program { static void Main(string[] args) { ThreadTest TK = new ThreadTest(); TK.Start(); Console.ReadKey(); } class ThreadTest { private Thread thread_1; private Thread thread_2; private List<int> tickets; private object objLock = new object();//对象锁的对象 /// <summary> /// 初始化线程实例 /// </summary> public ThreadTest() { thread_1 = new Thread(Run); thread_1.Name = "thread_1"; thread_2 = new Thread(Run); thread_2.Name = "thread_2"; } /// <summary> /// 新增票启动线程 /// </summary> 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 ticket = tickets[0]; Console.WriteLine("{0} :{1} ", Thread.CurrentThread.Name, ticket.ToString()); //移除 tickets.RemoveAt(0); //暂停单位毫秒 Thread.Sleep(1); } } } }
修改
public void Run() { while (tickets.Count > 0) { lock (objLock) { if (tickets.Count > 0) { //获取第一张票 int ticket = tickets[0]; Console.WriteLine("{0} :{1} ", Thread.CurrentThread.Name, ticket.ToString()); //移除 tickets.RemoveAt(0); //暂停单位毫秒 Thread.Sleep(1); } } } }
2.
class ThreadTest2 { public static List<int> tickets; private object objLock = new object();//对象锁的对象 /// <summary> /// 初始化票 /// </summary> static ThreadTest2() { tickets = new List<int>(100); for (int i = 1; i <= 100; i++) { tickets.Add(i); } } public void Run() { while (tickets.Count > 0) { lock (objLock) { if (tickets.Count > 0) { //获取第一张票 int ticket = tickets[0]; Console.WriteLine("{0} :{1} ", Thread.CurrentThread.Name, ticket.ToString()); //移除 tickets.RemoveAt(0); //暂停单位毫秒 Thread.Sleep(1); } } } } }
static void Main(string[] args) { //ThreadTest TK = new ThreadTest(); //TK.Start(); Thread thread_1 = new Thread(test); thread_1.Name = "thread_1"; Thread thread_2 = new Thread(test); thread_2.Name = "thread_2"; thread_1.Start(); thread_2.Start(); Console.ReadKey(); }
public static void test() { ThreadTest2 threadTest21 = new ThreadTest2(); threadTest21.Run(); }
修改:
private static object objLock = new object();//对象锁的对象
以上是关于多线程的主要内容,如果未能解决你的问题,请参考以下文章