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

资源同步

2019-11-08 18:22:27
字体:
来源:转载
供稿:网友
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的数值,并且不会重复。


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