c# 线程池实现 只是一个原理性的实现细节内容忽略
2021-07-01 05:03
标签:action down running bsp current result mes imp on() using System; namespace ThreadPoolImp //所有任务都放队列中,让工作线程来消费 private static HashSet private static List static bool shutdown = false; private void addThread(Action action) public void ShutDown() public void Run() public Action GetTask() } c# 线程池实现 只是一个原理性的实现细节内容忽略 标签:action down running bsp current result mes imp on() 原文地址:https://www.cnblogs.com/cppfans140812/p/9638055.html
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
{
public class MyThreadExcutor
{
//创建
private static volatile bool RUNNING = true;
private static ConcurrentQueue queue = null;
//工作线程数
int poolSize = 0;
//核心线程数(创建了多少个工作线程)
int coreSize = 0;
public MyThreadExcutor(int poolSize)
{
this.poolSize = poolSize;
queue = new ConcurrentQueue();
}
public void Exec(Action action)
{
if (action == null) { throw new ArgumentNullException(); }
if (coreSize {
addThread(action);
}
else
{
try
{
queue.Enqueue(action);
}
catch (Exception ex)
{
throw ex;
}
}
}
{
coreSize++;
Worker worker = new Worker(action);
workers.Add(worker);
Thread t = new Thread(worker.Run);
threadList.Add(t);
try
{
t.Start();
}
catch (Exception ex)
{
throw ex;
}
}
{
RUNNING = false;
if (workers.Count > 0)
{
foreach (Worker item in workers)
{
item.InterruptAll();
}
}
shutdown = true;
Thread.CurrentThread.Interrupt();
}
class Worker
{
private readonly static object lockObj = new object();
public Worker(Action action)
{
queue.Enqueue(action);
}
{
while (RUNNING)
{
if (shutdown==true)
{
Thread.CurrentThread.Interrupt();
}
Action task = null;
try
{
task = GetTask();
if (task != null)
{
task();
}
else
{
Thread.CurrentThread.Interrupt();
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
{
Action result;
queue.TryDequeue(out result);
return result;
}
public void InterruptAll()
{
for (int i = 0; i {
threadList[i].Interrupt();
}
}
}
}