乱七八糟 多线程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ParallelComputing
{
    public class MoreThread
    {
        private class ManualResetEventObj
        {
            public ManualResetEvent resetEvent
            {
                get;
                set;
            }

            public Object obj
            {
                get;
                set;
            }
        }

        private List<int> list;
        ManualResetEvent auto;
        long doneCount = 0;

        public MoreThread()
        {
            list = new List<int>();
        }

        public void Run()
        {
            Stack<int> stack = new Stack<int>();
            for (int i = 0; i < 60; i++)
            {
                stack.Push(i);
            }
            int temp = stack.Count;
            Console.WriteLine(temp);
            ManualResetEvent[] _manualResetEvents = new ManualResetEvent[temp];
            for (int i = 0; i < temp; i++)
            {
                Console.WriteLine("The Current Namber is {0}" + i);
                _manualResetEvents[i] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Star), (Object)new ManualResetEventObj()
                {
                    obj = i,
                    resetEvent = _manualResetEvents[i]
                });
            }
            WaitHandle.WaitAll(_manualResetEvents);
            Console.WriteLine("执行完成!");
        }

        private void Star(Object obj)
        {
            ManualResetEventObj e = obj as ManualResetEventObj;
            int i = Convert.ToInt32(e.obj);
            Monitor.Enter(obj);
            Thread thread = Thread.CurrentThread;
            System.Threading.Thread.Sleep(10);
            Console.WriteLine(i);
            list.Add(Convert.ToInt32(i));
            if (!thread.Equals(Thread.CurrentThread))
                throw new Exception("线程异常");
            Monitor.Exit(obj);
            e.resetEvent.Set();
        }
    }
}
posted @ 2012-06-01 11:28  Rhythmk  阅读(151)  评论(2编辑  收藏  举报
Rhythmk 个人笔记