zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }

  • 相关阅读:
    多线程等待
    多线程多进程
    Django中的 返回json对象的方式
    爬虫之 单线程+多任务异步协程
    python 调用github的api,呈现python的受欢迎的程度
    爬虫之线程池
    爬虫之代理和cookie的处理
    pip 安装报错
    git 新建仓库第一次提交
    ansible的剧本
  • 原文地址:https://www.cnblogs.com/wuhuisheng/p/2226307.html
Copyright © 2011-2022 走看看