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();
                    }
                }
            }
           
        }
    }
    

     运行测试结果

  • 相关阅读:
    N*N内递矩阵算法
    四舍五入算法C语言
    springboot整合hivejdbc遇到的坑
    Gradle 中 exclude group 关键字运用
    sparklocal运行异常Could not locate executable null\bin\winutils.exe in the Hadoop binaries
    大数据的五大关键技术
    opencv+python+pycharm实现人脸识别
    Python开源人脸识别库,识别率达99.38%!内附教程+源码分享
    Python实时语音识别控制
    JAVA操作鼠标和键盘
  • 原文地址:https://www.cnblogs.com/clc2008/p/6905714.html
Copyright © 2011-2022 走看看