万旬的博客

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  class TestThread
    {
        
        static void Main()
        {
            //使用WaitHandle静态方法阻止一个线程,直到一个或多个同步对象接收到信号
            WaitHandle[] waitHandles = new WaitHandle[] 
            {
            new ManualResetEvent(false),
            new ManualResetEvent(false)
            };

            WaitCallback waitCallback = new WaitCallback(MyThreadWork);

            WaitCallback waitCallback2 = new WaitCallback(MyThreadWork2);     // 增加线程工作类型

            ThreadPool.QueueUserWorkItem(waitCallback, "第一个线程");
            ThreadPool.QueueUserWorkItem(waitCallback, "第二个线程");

            MyState myState = new MyState("第三个线程", 100, waitHandles[0]); // 增加自定义的线程参数类型

            ThreadPool.QueueUserWorkItem(waitCallback2, myState);
            ThreadPool.QueueUserWorkItem(waitCallback2, new MyState("第四个线程", 2, waitHandles[1]));

            WaitHandle.WaitAll(waitHandles);

            Console.WriteLine("MyState 的 Number 值为: {0}", myState.Number);    // 读取线程改变后的 MyState
        }

        public static void MyThreadWork(object state)
        {
            Console.WriteLine("MyThreadWork 开始启动 …… {0}", (string)state);
            Thread.Sleep(1000);
            Console.WriteLine("运行结束…… {0}", (string)state);
        }

        // use MyState class 
        public static void MyThreadWork2(object state)
        {
            MyState myState = ((MyState)state);
            Console.WriteLine("MyThreadWork2 开始启动…… {0},{1}", ((MyState)state).Info, ((MyState)state).Number);
            Thread.Sleep(1000);
            ((MyState)state).Number += 1;      // 将 state的 Number 加 1
            Console.WriteLine("运行结束…… {0},{1}", ((MyState)state).Info, ((MyState)state).Number);
            ((ManualResetEvent)myState.DoneEvent).Set();
        }

    }

    public class MyState
    {
        private string info;
        private int number;
        private WaitHandle _doneEvent;


        public MyState(string info, int number, WaitHandle doneEvent)
        {
            this.info = info;
            this.number = number;
            this._doneEvent = doneEvent;
        }

        public string Info
        {
            get
            {
                return this.info;
            }
            set
            {
                this.info = value;
            }
        }

        public WaitHandle DoneEvent
        {
            get
            {
                return this._doneEvent;
            }
        }

        public int Number
        {
            get
            {
                return this.number;
            }
            set
            {
                this.number = value;
            }
        }
    }

 

程序运行结果截图

posted on 2014-04-28 23:17  蓝波崖  阅读(1873)  评论(0编辑  收藏  举报