📄 c9-05.cs
字号:
// 使用线程池调度线程示例
using System;
using System.Collections;
using System.Threading;
public class SomeState
{
public int Cookie;
public SomeState(int iCookie)
{
Cookie = iCookie;
}
}
public class Alpha
{
public Hashtable HashCount;
public ManualResetEvent eventX;
public static int iCount = 0;
public static int iMaxCount = 0;
public Alpha(int MaxCount)
{
HashCount = new Hashtable(MaxCount);
iMaxCount = MaxCount;
}
// Beta方法在线程池中有可用线程被调用
public void Beta(Object state)
{
// 输出当前线程的哈希码和cookie
Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(),
((SomeState)state).Cookie);
// lock关键字可以使不同级别的线程安全的切换
Console.WriteLine(
"HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}",
HashCount.Count,
Thread.CurrentThread.GetHashCode());
lock (HashCount)
{
if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
HashCount.Add (Thread.CurrentThread.GetHashCode(), 0);
HashCount[Thread.CurrentThread.GetHashCode()] =
((int)HashCount[Thread.CurrentThread.GetHashCode()])+1;
}
int iX = 2000;
Thread.Sleep(iX);
Interlocked.Increment(ref iCount);
if (iCount == iMaxCount)
{
Console.WriteLine();
Console.WriteLine("Setting eventX ");
eventX.Set();
}
}
}
public class SimplePool
{
public static int Main(string[] args)
{
Console.WriteLine("线程池示例:");
bool W2K = false;
// 在线程池中定义最多10个线程
int MaxCount = 10;
ManualResetEvent eventX = new ManualResetEvent(false);
Console.WriteLine("队列中有 {0} 个线程", MaxCount);
Alpha oAlpha = new Alpha(MaxCount);
oAlpha.eventX = eventX;
Console.WriteLine("线程池中的线程 0");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),
new SomeState(0));
W2K = true;
}
catch (NotSupportedException)
{
Console.WriteLine("在非win2000系统上运行错误");
W2K = false;
}
if (W2K) // 如果操作系统支持线程池
{
for (int iItem=1;iItem < MaxCount;iItem++)
{
Console.WriteLine("线程池中的线程 {0}", iItem);
ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));
}
Console.WriteLine("等待线程池资源耗尽");
// 调用eventX.Set()方法
eventX.WaitOne(Timeout.Infinite,true);
Console.WriteLine("线程池资源已经耗尽");
Console.WriteLine();
Console.WriteLine("通过线程载入");
foreach(object o in oAlpha.HashCount.Keys)
Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]);
}
return 0;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -