资源同步

using System;
using System.Collections;
using System.Threading;

namespace _15._3lock
{
    class Program
    {
        public static ArrayList arrNumber = new ArrayList();
        //添加100个数值
        public static void Add()
        {
            for (int i = 1; i <= 100; i++)
            {
                lock (arrNumber)
                {
                    if (!arrNumber.Contains(i))
                    {
                        arrNumber.Add(i);
                        Console.WriteLine("{0}添加样本数{1}",Thread.CurrentThread.Name,i);
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            Thread thread1 = new Thread(Add);
            thread1.Name = "线程1";
            Thread thread2 = new Thread(Add);
            thread2.Name = "线程2";
            Thread thread3 = new Thread(Add);
            thread3.Name = "线程3";
            //开始执行
            thread1.Start();
            thread2.Start();
            thread3.Start();

            Console.ReadKey();
        }
    }
}

这里写图片描述
使用lock只能操作引用类型的数,lock(arrNumber){}确保了对arrNumber使用的同步,代码中我们确保了多个线程同时在arrNumber 中添加1-100的数值,并且不会重复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值