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

    引用:http://jingyan.baidu.com/article/0eb457e50949d203f1a9050f.html

    先说是一下  ManualResetEvent 是一线程用来控制别一个线程的信号。大家可以把它看成 操作系统原理中说到的pv操作如下图所说是 ManualResetEvent 对象起一个信使的作用。

    ManualResetEvent 对象的两个控制方法。

    1、this.manualEvent.Reset(); //将事件状态设置为非终止状态,导致线程阻止。

    2、this.manualEvent.Set();   //将事件状态设置为终止状态,允许一个或多个等待线程继续。

    说了这么多光说不做还真没有用,接下来看代码!

     1 public class MyThread
     2 {
     3     Thread t = null;
     4     ManualResetEvent manualEvent = new ManualResetEvent(true);//为trur,一开始就可以执行
     5 
     6     private void Run()
     7     {
     8         while (true)
     9         {
    10             this.manualEvent.WaitOne();
    11             Console.WriteLine("Thread Id:{0},Name:{1}.", Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.Name);
    12             Thread.Sleep(1000);
    13         }
    14     }
    15 
    16     public void Start()
    17     {
    18         this.manualEvent.Set();
    19     }
    20 
    21     public void Stop()
    22     {
    23         this.manualEvent.Reset();
    24     }
    25 
    26     public MyThread(string threadName="thread001")
    27     {
    28         t = new Thread(this.Run);
    29         t.Name = threadName;
    30         t.Start();
    31     }
    32 
    33 } 
    View Code

    调用方法:

     1 class Program
     2 {
     3     static void Main(string[] args)
     4     {
     5         MyThread myt = new MyThread("MyThread001");
     6 
     7         while (true)
     8         {
     9             Console.WriteLine("输入 stop后台线程挂起 start 开始执行!");
    10             string str = Console.ReadLine();
    11             if (str.ToLower().Trim() == "stop")
    12             {
    13                 myt.Stop();
    14             }
    15 
    16             if (str.ToLower().Trim() == "start")
    17             {
    18                 myt.Start();
    19             }
    20         }
    21     }
    22 }
    View Code

    调用流程:

  • 相关阅读:
    3.2 线程复用:线程池
    3.1.7 线程阻塞工具类:LockSupport
    3.1.6 循环栅栏:CyclicBarrier
    3.1.4 读写锁
    3.1.5 倒计时器:CountDownLatch
    3.1.3 允许多个线程同时访问:信号量
    3.1.2 condition 条件
    3.1.1 重入锁 以及源码分析
    2.8.4 错误的加锁
    jsp中 scope="application" 表示
  • 原文地址:https://www.cnblogs.com/xzxBlog/p/4605275.html
Copyright © 2011-2022 走看看