如何做jquery音乐网站,WordPress代码改silder,品牌网站如何做,沛县做网站在使用线程池时#xff0c;当用线程池执行多个任务时#xff0c;由于执行的任务时间过长#xff0c;会导制两个任务互相执行#xff0c;如果两个任务具有一定的操作顺序#xff0c;可能会导制不同的操作结果#xff0c;这时#xff0c;就要将线程池按顺序操作。下面先给…在使用线程池时当用线程池执行多个任务时由于执行的任务时间过长会导制两个任务互相执行如果两个任务具有一定的操作顺序可能会导制不同的操作结果这时就要将线程池按顺序操作。下面先给一段代码该代码是不按顺序对线程池进行操作的代码如下 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication1{class Program{static void Main(string[] args){AutoResetEvent autoEvent new AutoResetEvent(false);ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);Console.ReadLine();}static void ThreadMethod(object stateInfo){for (int i 0; i 100;i )Console.WriteLine(ThreadOne, executing ThreadMethod, is {0}from the thread pool., Thread.CurrentThread.IsThreadPoolThread ? : not );}static void WorkMethod(object stateInfo){for (int i 0; i 100; i)Console.WriteLine(ThreadTwo, executing WorkMethod);}}} 运行结果如图1、图2所示。 图1 运行结果的上半部 图2 运行结果的下半部 从图1、图2可以看出在使用线程池对线程进行操作时由于各任务的时间过长多个任务的线程可能会交互操作那么如何才能将线程池按指定的顺序进行操作呢主要是用AutoResetEvent类来实现的。 可以用AutoResetEvent类的WaitOne方法阻止线程然后只执行当前操作的线程池当遇到AutoResetEvent类的Set方法后将当前线程设置为终止状态执行其他等待的线程。修改后的代码如下 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication1{class Program{static void Main(string[] args){AutoResetEvent autoEvent new AutoResetEvent(false);ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);autoEvent.WaitOne();ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);autoEvent.WaitOne();Console.ReadLine();} static void ThreadMethod(object stateInfo){for (int i 0; i 100;i )Console.WriteLine(ThreadOne, executing ThreadMethod, is {0}from the thread pool., Thread.CurrentThread.IsThreadPoolThread ? : not );((AutoResetEvent)stateInfo).Set();}static void WorkMethod(object stateInfo){for (int i 0; i 100; i)Console.WriteLine(ThreadTwo, executing WorkMethod);((AutoResetEvent)stateInfo).Set();}}} 运行结果如下 转载于:https://www.cnblogs.com/DonetRen/p/10177339.html