zoukankan      html  css  js  c++  java
  • ManualResetEvent和AutoResetEvent的区别实例

    ManualResetEvent和AutoResetEvent的作用可以理解为在线程执行中插入停顿点flag终止程序运行,然后通过设置flag的状态来使得程序继续运行。

    两者的区别是:ManualResetEvent设置flag状态为可以运行后,所有在终止点的程序都可以继续运行;AutoResetEvent设置flag状态后,只会有一个程序继续运行(如果AutoResetEvent设置的flag有100个程序在等待,那flag开始状态必须要设置100次才能使得所有的线程都执行完毕)

    示例如下(ManualResetEvent时会同时执行三个线程,AutoResetEvent则会依次执行):

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Data;
    
    public class Example
    {
    
        /// <summary>
    
        /// 预备信号,准备发送,初始化
    
        /// </summary>
    
        public EventWaitHandle flag;
        public void Begin()
        {
            //flag = new ManualResetEvent(false);
            flag = new AutoResetEvent(false);
            Thread th1 = new Thread(() =>
            {
                flag.WaitOne();
                 Thread.Sleep(1000);
               Console.WriteLine("第一个线程已经通过……");
                flag.Set();
    
            });
    
    
    
            Thread th2 = new Thread(() =>
            {
                flag.WaitOne();
                 Thread.Sleep(1000);
               Console.WriteLine("第二个线程已经通过……");
                flag.Set();
    
            });
    
    
            Thread th3 = new Thread(() =>
            {
                flag.WaitOne();
                Thread.Sleep(1000);
                Console.WriteLine("第三个线程已经通过……");
               flag.Set();
    
            });
    
            th1.IsBackground = true;
             th1.Start();
             th2.IsBackground = true;
             th2.Start();
            th3.IsBackground = true;
             th3.Start();
             flag.Set();
            Thread.Sleep(1000);
     
            Console.WriteLine("A");
            Console.WriteLine("B");
    
        }
    
    
    
        static void Main(string[] args)
        {
            new Example().Begin();
            Console.ReadKey();
        }
    }
  • 相关阅读:
    第四章、Vue组件
    第三章、Vue实例
    第二章、Vue指令
    Python练习实例012
    Python练习实例011
    Python练习实例010
    Python练习实例009
    Python练习实例008
    Python练习实例007
    Python练习实例006
  • 原文地址:https://www.cnblogs.com/thaughtZhao/p/4227079.html
Copyright © 2011-2022 走看看