zoukankan      html  css  js  c++  java
  • c#多线程(一)

    对于线程操作,一直没有特别的会用。自己写了些代码:贴出来大家分享。

    代码

            
    #region 简单线程,主线程与子线程threadAnther,局部变量互不影响

            
    static void SilmpleMultThread()
            {
                Thread threadAnther 
    = new Thread(new ThreadStart(WrietConsole));
                threadAnther.Start();
    //新线程启动,
                while (true) Console.Write("Y");//主线程不停的写 “Y”
            }

            
    static void WrietConsole()
            {
                
    while(true) Console.Write("X");//不停的写“X”
            }
            
    #endregion

            
    #region 副本分别在各自的内存堆栈中创建

            
    static void SimpleShareMultThread()
            {
                
    //变量x的副本分别在各自的内存堆栈中创建,输出也一样;
                Thread threadAnther = new Thread(new ThreadStart(Go));
                threadAnther.Start();
                Go();
            }

            
    static void Go()
            {
                
    //声明和使用同一个局部变量 x
                for (int x = 0; x < 5; x++)
                    Console.Write(
    "*");
            }

            
    #endregion

            
    #region 多个线程引用了一些公用的目标实例的时候,他们共享数据

            
    static void SimpleShareMuliThead()
            {
                
    //两个线程都调用OutPut方法,他们共享done字段。输出结果是一个Done
                Program prgoram = new Program();
                prgoram.OutPut();
                Thread threadAnother 
    = new Thread(new ThreadStart(prgoram.OutPut));
                threadAnother.Start();
            }

            
    bool done;

            
    public void OutPut()
            {
                
    if (!done) { done = true; Console.Write("Done"); }
            }

            
    #endregion

            
    #region 静态字段提供了另一种线程之间的共享数据

            
    static bool outDone; //静态字段,为所有线程共享
            static object locker = new object();

            
    static void SimpleShareStaticMulThead()
            {
                Thread threadAnother 
    = new Thread(OutDoneFunction);//线程初始化的另一种方法
                threadAnother.Start();
                OutDoneFunction();
            }

            
    static void OutDoneFunction()
            {
                
    //if (!outDone) { Console.Write("Done"); outDone = true; } //这种情况打印出两个“Done”
                lock (locker)
                {
                    
    if (!outDone) { Console.Write("Done"); outDone = true; } 
                }
    //为了避免这种情况,用lock,锁机制,确定同一时刻只有一个线程进入临界区
                
    //  if (!outDone) {  outDone = true; Console.Write("Done");  } //这种情况打印出一个“Done”
            }

            
    #endregion
  • 相关阅读:
    linux sar 命令详解
    linux perf
    Linux下的内核测试工具——perf使用简介
    系统级性能分析工具 — Perf
    使用truss、strace或ltrace诊断软件的“疑难杂症”
    6.数组类型和数组指针类型
    5.二级指针
    4.const
    3.字符串
    C/C++ 错误笔记-如果要释放内存,必须拿到内存的首地址进行释放
  • 原文地址:https://www.cnblogs.com/csharponworking/p/1621470.html
Copyright © 2011-2022 走看看