c#多線程(一)

來源:互聯網
上載者:User

對於線程操作,一直沒有特別的會用。自己寫了些代碼:貼出來大家分享。

代碼


        #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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.