回复 13# xczxczxcz
线程本身是并行的,会占用cpu资源,当线程被锁住时,cpu资源将被释放。
C# 示例- using System;
- using System.Threading;
-
- class Test
- {
- static void Main()
- {
- int PoolSize = Environment.ProcessorCount; // 获取当前计算机上的处理器数。
-
- EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset); // 事件锁
-
- Thread[] ThreadPool = new Thread[PoolSize];
-
- for (sbyte i=0; i<PoolSize; i++)
- {
- ThreadPool[i] = new Thread(Occupy);
- ThreadPool[i].IsBackground = true;
- }
- for (sbyte i=0; i<PoolSize; i++)
- ThreadPool[i].Start(ewh);
-
- while (true)
- {
- Console.Write("1 占用cpu资源\n2 释放cpu资源\n");
- string input = Console.ReadLine();
- if (input == "1")
- {
- ewh.Set();
- }
- else if (input == "2")
- {
- ewh.Reset();
- }
- }
- }
-
- static void Occupy(object EventLock)
- {
- EventWaitHandle el = EventLock as EventWaitHandle;
- while (true)
- {
- el.WaitOne();
- }
- }
-
- }
复制代码
|