zoukankan      html  css  js  c++  java
  • test

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;

    namespace TestThread
    {
    class Program
    {
    private static Queue<int> data_int = new Queue<int>();

    private static Mutex mtx = new Mutex();

    private static int i = 0;

    private static void write()
    {
    while (true)
    {
    try
    {
    Monitor.Enter(mtx);
    data_int.Enqueue(i);
    Console.WriteLine("write:"+i);
    i++;
    }
    finally
    {
    Monitor.Exit(mtx);
    }
    Monitor.Pulse(mtx);
    Thread.Sleep(30000);//模拟外部数据,1秒获得一次
    }
    }

    private static void read()
    {
    while (true)
    {
    try
    {
    Monitor.Enter(mtx);
    bool hasData = data_int.Count > 0;
    if(!hasData)
    {
    Monitor.Wait(mtx, -1, false);
    }
    if (data_int.Count > 0)
    {
    int i = data_int.Dequeue();
    Console.WriteLine("read"+i);
    }
    }
    finally
    {
    Monitor.Exit(mtx);
    }
    }
    }

    static void Main(string[] args)
    {
    Thread read1 = new Thread(read);
    read1.Name = "read1";
    read1.Start();

    Thread read2 = new Thread(read);
    read2.Name = "read2";
    read2.Start();

    Thread write1 = new Thread(write);
    write1.Name = "write1";
    write1.Start();

    //Thread write2 = new Thread(write);
    //write2.Start();

    }
    }
    }

  • 相关阅读:
    dom 获取节点练习
    dom 节点的添加删除 与修改
    dom document属性练习
    ArrayList 去除重复元素
    ud类型聊天
    UDP数据发送
    指定标签所在div在新窗口打开
    日期Calendar
    Seraph介绍
    U盘cmd命令行修复
  • 原文地址:https://www.cnblogs.com/lsfv/p/8547295.html
Copyright © 2011-2022 走看看