zoukankan      html  css  js  c++  java
  • C# 使用 AutoResetEvent 或 ManualResetEvent 同步两个线程

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading;
     6 
     7 namespace ThreadTest
     8 {
     9     class Program
    10     {
    11         // 信号 
    12         static AutoResetEvent ar = new AutoResetEvent(false);
    13 
    14         // 一个公用的变量
    15         static int i = 0;
    16 
    17         // Thread Method 1
    18         static void WriteMethod(object state) {
    19             while (i < 10) {
    20                 Thread.Sleep(1000);
    21                 i++;
    22                 //Console.WriteLine("{1} Write i : {0}", i, Thread.CurrentThread.Name);
    23                 Console.WriteLine("{1} Write i : {0}", i, (string)state);
    24                 ar.Set();
    25             }
    26         }
    27 
    28         // Thread Method 2
    29         static void ReadMethod(object state) {
    30             while (true) {
    31                 ar.WaitOne();
    32                 //Console.WriteLine("{1} Read i : {0}", i, Thread.CurrentThread.Name);
    33                 Console.WriteLine("{1} Write i : {0}", i, (string)state);
    34             }
    35         }
    36 
    37         static void Main(string[] args) {
    38             // 开启 写入线程
    39             // 线程池方法
    40             ThreadPool.QueueUserWorkItem(WriteMethod,"Write Thread ");
    41 
    42             // 普通开线程方法
    43             //Thread write = new Thread(new ThreadStart(WriteMethod));
    44             //write.Name = "Write Thread ";
    45 
    46             // 如果是后台线程,需要 一个 Console.ReadKey 等待
    47             //write.IsBackground = true;
    48             //write.Start();
    49 
    50             // 开启 读取线程
    51             // 线程池方法
    52             ThreadPool.QueueUserWorkItem(ReadMethod,"Read Thread ");
    53 
    54             // 普通开线程方法
    55             //Thread read = new Thread(new ThreadStart(ReadMethod));
    56             //read.Name = "Read Thread ";
    57 
    58             // 如果是后台线程,需要 一个 Console.ReadKey 等待
    59             //read.IsBackground = true;
    60             //read.Start();
    61 
    62             // 如果使用线程池方法的时候.线程都是 后台线程. Console 会立即结束.所以需要这个方法来阻塞主线程
    63             Console.ReadKey();
    64         }
    65     }
    66 }
  • 相关阅读:
    HDU 4709 3-idiots FFT 多项式
    多项式的黑科技
    JZYZOJ 2043 多项式除法和取余 NTT 多项式
    JZYZOJ 2042 多项式逆元 NTT 多项式
    网络爬虫(4)--正则表达式
    网络爬虫(3)--Beautiful页面解析
    网络爬虫(2)--异常处理
    网络爬虫(1)--准备工作
    PCL库配置出现的问题(WIN10+VS2013)
    QT笔记(1)--QT编程环境搭建
  • 原文地址:https://www.cnblogs.com/easyfrog/p/3141255.html
Copyright © 2011-2022 走看看