多线程的使用

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类型
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值