zoukankan      html  css  js  c++  java
  • ManualResetEvent 用法

    第一、简单介绍

        ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 Reset 以将 ManualResetEvent 置于非终止状态,此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。

    当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,ManualResetEvent 将保持终止状态(即对 WaitOne 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,

    如果初始状态处于终止状态,为 true;否则为 false。

    第二、代码演示

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
        class MyThread
        {
            Thread t = null;
            ManualResetEvent manualEvent = new ManualResetEvent(true);//为trur,一开始就可以执行
            private void Run()
            {
                while (true)
                {
                    this.manualEvent.WaitOne();
                    Console.WriteLine("线程id:{0}", Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(2000);
                }
            }
    
            public void Start()
            {
                this.manualEvent.Set();
            }
    
            public void Stop()
            {
                this.manualEvent.Reset();
            }
    
            public MyThread()
            {
                t = new Thread(this.Run);
                t.Start();
            }
    
        }
    
        class Program
        {     
            static void Main(string[] args)
            {
                MyThread myt = new MyThread();           
                while (true)
                {
                    Console.WriteLine("输入 stop 后台线程挂起 start 开始执行!");
                    string str = Console.ReadLine();
                    if (str.ToLower().Trim() == "stop")
                    {
                        Console.WriteLine("线程停止运行...
    ");
                        myt.Stop();
                    }
                    if (str.ToLower().Trim() == "start")
                    {
                        Console.WriteLine("线程开启运行...
    ");
                        myt.Start();
                    }
                }
            }
           
        }
    }
    

     运行测试结果

  • 相关阅读:
    [加密]公钥密码学和对称加密
    [加密]公钥/私钥/数字签名理解
    [加密]对称加密和非对称加密
    [进程]kill 9和15,以及pkill, killall
    [服务]Crontab和每隔10S执行一次
    sh脚本异常:/bin/sh^M:bad interpreter: No such file or directory
    前端利器躬行记(2)——Babel
    前端利器躬行记(1)——npm
    React躬行记(13)——React Router
    React躬行记(12)——Redux中间件
  • 原文地址:https://www.cnblogs.com/clc2008/p/6905714.html
Copyright © 2011-2022 走看看