线程同步:InterLocked 锁

例子1:

namespace GCApp
{
    class Program
    {
        private static readonly object o = new object();
        static void Main(string[] args)
        {
            TicketSeller t = new TicketSeller("张三");
            TicketSeller t1 = new TicketSeller("李四");

            Console.ReadKey();
        }
    }
    public class TicketSeller
    {
        static int signal = 0;
        static int count = 100;
        public TicketSeller(string name)
        {
            Thread t = new Thread(Sell);
            t.Name = name;
            t.IsBackground = true;
            t.Start();

        }

        public void Sell()
        {
            while (count > 0)
            {
                if (0 == Interlocked.Exchange(ref signal, 1))//加锁
                {
                    TicketSeller.count--;
                    //Interlocked.Decrement(ref count);也可以用总方式来进行自减
                    Console.WriteLine("{0}卖出一张票,还有{1}张", Thread.CurrentThread.Name, count);

                    Interlocked.Exchange(ref signal, 0); //解锁
                }
            }
        }
    }
}

 

列子2:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static int count = 100; //这个int必须是静态的
        static int signal = 0; //这个int必须是静态的
        static void Main(string[] args)
        {
            for (int i = 0; i < 50; i++)
            {
                //通过Interlocked实现自旋锁。
                Task.Run(new Action(new Program().Subtraction));
                Task.Run(new Action(new Program().Subtraction));
            }
            Console.ReadKey();
        }       
        public void Subtraction()
        {
            while (Interlocked.Exchange(ref signal, 1) != 0) { }//加自旋锁

            Program.count--;  //业务操作
            Console.WriteLine(count);

            Interlocked.Exchange(ref signal, 0);  //释放锁
        }
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值