复制以下代码,直接运行测试便可知晓。
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApp.多线程
{
class Program
{
static object s_objLock = new object();
static List<int> s_tickets = new List<int>();
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
s_tickets.Add(i + 1);
}
ThreadPoolTicketing();
ThreadTicketing();
Console.ReadKey();
}
static void ThreadPoolTicketing()
{
ThreadPool.SetMaxThreads(5, 5);
ThreadPool.SetMinThreads(1, 1);
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) => { Ticketing(); }));
}
}
static void ThreadTicketing()
{
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(new ThreadStart(Ticketing));
thread.Start();
}
}
static void Ticketing()
{
while (s_tickets.Count > 0)
{
lock (s_objLock)
{
if (s_tickets.Count > 0)
{
Console.WriteLine($"{ Thread.CurrentThread.ManagedThreadId} ticketing ,ticket number :{s_tickets[0]} ");
s_tickets.RemoveAt(0);
}
}
}
}
}
}