悟生慧

 

C#多线程间同步-实例 原文:http://blog.csdn.net/zhoufoxcn/article/details/2453803

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

namespace ThreadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadDemo demo = new ThreadDemo(1000);
            demo.Action();
        }
    }
    /// <summary>
    /// 线程同步的实例
    /// </summary>
    public class ThreadDemo
    {
        private Thread threadOne;
        private Thread threadTwo;

        private ArrayList stringList;

        private event EventHandler OnNumberClear;


        public ThreadDemo(int Number)
        {
            Random random = new Random(1000000);//随机数
            stringList = new ArrayList(Number);//指定初始容量

            for (int i = 0; i < Number; i++)
            {
                stringList.Add(random.Next().ToString());//添加对象
            }
            threadOne = new Thread(Run);//两个线程共同做一件事情
            threadTwo = new Thread(Run);//两个线程共同做一件事情

            threadOne.Name = "线程1";
            threadTwo.Name = "线程2";

            OnNumberClear+=new EventHandler(ThreadDemo_OnNumberClear);
        }

        /// <summary>
        /// 开始工作
        /// </summary>
        public void Action()
        {
            threadOne.Start();
            threadTwo.Start();//
        }

        private void Run()
        {
            string StringValue = null;

            while (true)
            {
                Monitor.Enter(this);//锁定 保持同步
                StringValue=(string)stringList[0];
                Console.WriteLine(Thread.CurrentThread.Name + "删除" + StringValue);
                stringList.RemoveAt(0);

                if (stringList.Count == 0)
                {
                    OnNumberClear(this,new EventArgs());//引发完成事件
                }
                Monitor.Exit(this);
                Thread.Sleep(5);
            }
          

        }
        /// <summary>
        /// 停止执行线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ThreadDemo_OnNumberClear(object sender,EventArgs e)
        {
            Console.WriteLine("执行完毕,停止了所有线程的执行");
            threadOne.Abort();
            threadTwo.Abort();
        }
    }
}

posted on 2011-10-27 11:58  悟生慧  阅读(262)  评论(0编辑  收藏  举报

导航