zoukankan      html  css  js  c++  java
  • 六 c# 多线程研究 线程间通信

    using System;
    using System.Text;
    using System.Threading;

    namespace ThreadTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student student = new Student();
                new Thread(new ThreadStart(new Thread1(student).run)).Start();//添加信息
                new Thread(new ThreadStart(new Thread2(student).run)).Start();//读取信息
            }
        }

        /// <summary>
        /// 向Student类加添加信息
        /// </summary>
        public class Thread1
        {
            private Student student;
            public Thread1(Student student)
            {
                this.student = student;
            }
            public void run()
            {
                int i = 0;
                while (true)
                {
                    if (i == 0)
                        student.Add("jxncwzb", 23);
                    else
                        student.Add("jxncwzb++", 22);
                    i = (i + 1) % 2;
                }
            }
        }

        /// <summary>
        /// 读取Thread1干才添加的信息
        /// </summary>
        public class Thread2
        {
            private Student student;
            public Thread2(Student student)
            {
                this.student = student;
            }
            public void run()
            {
                while (true)
                {
                    student.GetInfo();
                }
            }
        }

        public class Student
        {
            private string name;
            private int age;
            private bool isRun = false;
            public void Add(string name, int age)
            {
                Monitor.Enter(this);
                if (isRun)
                    Monitor.Wait(this);
                this.name = name;
                //Thread.Sleep(10);
                this.age = age;
                this.isRun = true;
                Monitor.Pulse(this);
                Monitor.Exit(this);
            }

            public void GetInfo()
            {
                Monitor.Enter(this);
                if (!isRun)
                    Monitor.Wait(this);
                Console.Write("姓名:" + name);
                Console.WriteLine("&年龄:" + age.ToString());
                this.isRun = false;
                Monitor.Pulse(this);
                Monitor.Exit(this);
            }

        }
    }

  • 相关阅读:
    001:大盗阿福
    1183 编辑距离(51NOD)(dp)
    1134 最长递增子序列(容易TLE)
    1181 质数中的质数(质数筛法)(51NOD基础)
    列表行拖拽效果
    10个提升iOS开发效率的必用工具
    无需转化直接使用ESD映像文件安装系统简明教程
    Objective-C中变量采用@property的各个属性值的含义
    struts接收参数方式
    c# 执行js的方法
  • 原文地址:https://www.cnblogs.com/pricks/p/1590546.html
Copyright © 2011-2022 走看看