由二部分組成,一個線程管理類ThreadManager,一個線程類MyThread Test類是用來測試的
參考了以下資料:
http://tech.ccidnet.com/pub/disp/Article?columnID=294&articleID=33440&pageNO=1
http://soft.yesky.com/SoftChannel/72342371961929728/20041013/1863707.shtml
下面是代碼,希望大家提出更好的建議:
1.ThreadManager.cs
using System;
using System.Threading;
using System.Collections;
namespace CustomThreadPool
{
///
/// 線程管理器,會開啟或喚醒一個線程去執(zhí)行指定的回調(diào)方法
///
public class ThreadManager
{
private static ArrayList threadList = new ArrayList(); //線程列表,靜態(tài)
//不允許創(chuàng)建實例
private ThreadManager()
{
}
///
/// 靜態(tài)方法,開啟或喚醒一個線程去執(zhí)行指定的回調(diào)方法
///
/// 委托實例
/// 傳遞給回調(diào)方法的參數(shù)
/// 當(dāng)沒有可用的線程時的等待時間,以毫秒為單位
///
public static bool QueueUserWorkItem(WaitCallback waitCallback, Object obj, int timeOut)
{
//鎖住共享資源,實現(xiàn)線程安全
lock(threadList)
{
try
{
//如果線程列表為空,填充線程列表
if (threadList.Count == 0)
{
InitThreadList();
}
long startTime = DateTime.Now.Ticks;
do
{
//遍歷線程列表,找出可用的線程
foreach(MyThread myThread in threadList)
{
//線程為空,需要創(chuàng)建線程
if (myThread.T == null)
{
myThread.Start(waitCallback, obj, false);
return true;
}
else if (myThread.T.ThreadState == ThreadState.Suspended)
{//線程為掛起狀態(tài),喚醒線程
myThread.Start(waitCallback, obj, true);
return true;
}
}
//在線程 Sleep 前釋放鎖
Monitor.PulseAll(threadList);
Thread.Sleep(500);
}while (((DateTime.Now.Ticks - startTime) / 10000) < timeOut);
}
finally
{
Monitor.Exit(threadList);
}
}
return false;
}
//使用 MyThread 對象填充線程列表,注意,這個時候線程并沒有啟動
參考了以下資料:
http://tech.ccidnet.com/pub/disp/Article?columnID=294&articleID=33440&pageNO=1
http://soft.yesky.com/SoftChannel/72342371961929728/20041013/1863707.shtml
下面是代碼,希望大家提出更好的建議:
1.ThreadManager.cs
using System;
using System.Threading;
using System.Collections;
namespace CustomThreadPool
{
///
/// 線程管理器,會開啟或喚醒一個線程去執(zhí)行指定的回調(diào)方法
///
public class ThreadManager
{
private static ArrayList threadList = new ArrayList(); //線程列表,靜態(tài)
//不允許創(chuàng)建實例
private ThreadManager()
{
}
///
/// 靜態(tài)方法,開啟或喚醒一個線程去執(zhí)行指定的回調(diào)方法
///
/// 委托實例
/// 傳遞給回調(diào)方法的參數(shù)
/// 當(dāng)沒有可用的線程時的等待時間,以毫秒為單位
///
public static bool QueueUserWorkItem(WaitCallback waitCallback, Object obj, int timeOut)
{
//鎖住共享資源,實現(xiàn)線程安全
lock(threadList)
{
try
{
//如果線程列表為空,填充線程列表
if (threadList.Count == 0)
{
InitThreadList();
}
long startTime = DateTime.Now.Ticks;
do
{
//遍歷線程列表,找出可用的線程
foreach(MyThread myThread in threadList)
{
//線程為空,需要創(chuàng)建線程
if (myThread.T == null)
{
myThread.Start(waitCallback, obj, false);
return true;
}
else if (myThread.T.ThreadState == ThreadState.Suspended)
{//線程為掛起狀態(tài),喚醒線程
myThread.Start(waitCallback, obj, true);
return true;
}
}
//在線程 Sleep 前釋放鎖
Monitor.PulseAll(threadList);
Thread.Sleep(500);
}while (((DateTime.Now.Ticks - startTime) / 10000) < timeOut);
}
finally
{
Monitor.Exit(threadList);
}
}
return false;
}
//使用 MyThread 對象填充線程列表,注意,這個時候線程并沒有啟動