日期:2014-05-20  浏览次数:20894 次

多线程
刚在网上开到一个线程控制的问题,用3个线程输出1,2,3,4,5,...75,第一个线程输出1,2,3,4,5 然后第二个线程输出6,7,8,9,10...依次这样输出 到第三个线程输出75为止。
------解决方案--------------------
这不是考线程,是考线程同步对象的使用……

using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
ManualResetEvent[] MREs = new ManualResetEvent[3]; 
int i;
for (i = 0;i < 3;i++)
{
MREs[i] = new ManualResetEvent(false);
}
for (i = 0;i < 15;i += 5)
{
ThreadPool.QueueUserWorkItem(state =>
{
int x = (int)state;
for (int j = 1;j <= 75;j++)
{
MREs[x / 5].WaitOne();
if ((((j - 1) % 15) - x < 5) && (((j - 1) % 15) - x >= 0))
Console.WriteLine(j);
if (j % 5 == 0)
{
MREs[x / 5].Reset();
MREs[(x / 5 + 1) % 3].Set();
}
}
MREs[x / 5].Set();
}, i);
}
MREs[0].Set();
WaitHandle.WaitAll(MREs);
Console.ReadLine();
}
}

这种应试教育一般的题目,出题者一定深受应试教育毒害,这一定是体制问题,最终吃亏的总是屁民,我不由得陷入深深的沉思当中。