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的数值,并且不会重复。