lock(obj)锁的使用
个人学习总结:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace product
{
class Program
{
static void Main(string[] args)
{
Myconnection[] connec = new Myconnection[100];
int index = 0;
for (int i = 0; i < 15; i++)
{
Thread thread = new Thread(() => {
while (true)
{
lock (connec)
{
if (index < 99)
{
connec[index] = new Myconnection();
Console.WriteLine("生产者: " + index);
index++;
}
}
Thread.Sleep(1000);
}
});
thread.IsBackground = true;
thread.Start();
}
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(() => {
while (true)
{
lock (connec)
{
if (index > 0)
{
connec[index - 1] = null;
Console.WriteLine("消费者: " + index);
index--;
}
}
Thread.Sleep(50);
}
});
thread.IsBackground = true;
thread.Start();
}
Console.ReadLine();
}
}
public class Myconnection
{
}
}