当前位置: 代码迷 >> .NET Framework >> 多线程,该如何处理
  详细解决方案

多线程,该如何处理

热度:20   发布时间:2016-05-02 00:21:03.0
多线程
刚在网上开到一个线程控制的问题,用3个线程输出1,2,3,4,5,...75,第一个线程输出1,2,3,4,5 然后第二个线程输出6,7,8,9,10...依次这样输出 到第三个线程输出75为止。

------解决方案--------------------
这不是考线程,是考线程同步对象的使用……
C# code
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();    }}
  相关解决方案