首页 > 学院 > 开发设计 > 正文

多线程的使用

2019-11-08 18:28:16
字体:
来源:转载
供稿:网友
using System;using System.Threading;namespace _15._1thread{ class PRogram { public static void Test() { Console.WriteLine("{0}正在执行测试方法",Thread.CurrentThread.Name); } static void Main(string[] args) { ThreadStart threadWork = new ThreadStart(Test); Thread thread1 = new Thread(threadWork); thread1.Name = "线程1"; Thread thread2 = new Thread(threadWork); thread2.Name = "线程2"; Thread thread3 = new Thread(threadWork); thread3.Name = "线程3"; //开始执行 thread3.Start(); thread2.Start(); thread1.Start(); Console.ReadKey(); } }}

一个可能的情况,因为多线程是并行的,不能确定每一次具体的运行情况 这里写图片描述 volatile易失域,多线程-卖票系统

using System;using System.Threading;namespace _15._2volatile{ class Program { //定义易失域 车票数量 public volatile static int tickets = 10; //卖票 public static void SellTickets() { //票数大于10才能继续卖票 while (tickets>0) { tickets--; Console.WriteLine("{0},卖了一张票,剩余票数{1}",Thread.CurrentThread.Name,tickets); } } static void Main(string[] args) { Thread thread1 = new Thread(SellTickets); thread1.Name = "窗口1"; Thread thread2 = new Thread(SellTickets); thread2.Name = "窗口2"; Thread thread3 = new Thread(SellTickets); thread3.Name = "窗口3"; //开始执行 thread1.Start(); thread2.Start(); thread3.Start(); Console.ReadKey(); } }}

使用3个线程模拟3个售票窗口,虽然线程是并发的,但是他们对于易失域的访问时需要排队的,所以不会出现多卖票或者少卖票的情况, 可以定义为易失域的数据类型为:引用类型,数据值类型,枚举类型和bool类型 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表