執行緒的掛起與恢復

iamzxf發表於2015-05-26

    C#中,執行緒的掛起與恢復是通過Suspend()和Resume()方法實現的。通過下面的例子來說明。

    編寫主執行緒呼叫子執行緒,通過類的方法輸出26個大寫英文字母,在主執行緒內部分別呼叫Suspend()和Resume()方法。
     (1)定義一個類SuspendText,通過其方法Method實現26個字母的輸出,每輸出一行暫停0.5秒。
     (2)主調函式讓子執行緒執行1秒後掛起,主執行緒執行1秒後再喚醒子執行緒繼續執行。
     (3)子執行緒執行完畢後,主執行緒結束。

參考程式碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace threadJoin3
{

    class Program
    {
        static void Method()
        {
            Console.WriteLine("{0}執行緒啟動", Thread.CurrentThread.Name);
            int i = 1;
            while (i <= 26)
            {
                Console.Write(Convert.ToChar(i + Convert.ToInt32('A') - 1) + "\t");
                if (i % 8 == 0)
                {
                    Console.WriteLine();
                    Thread.Sleep(500);
                }
                i++;
            }
            Console.WriteLine("\n{0}執行緒結束",Thread.CurrentThread.Name);
        }

        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "主執行緒";
            Console.WriteLine("{0}執行緒啟動",Thread.CurrentThread.Name);
            Thread myThread = new Thread(new ThreadStart(Method));
            myThread.Name = "子執行緒";
            myThread.Start();
            Thread.Sleep(1000);
            myThread.Suspend();
            Console.WriteLine("\n掛起{0}執行緒",myThread.Name);
            Thread.Sleep(1000);
            myThread.Resume();
            Console.WriteLine("\n喚醒{0}執行緒", myThread.Name);
            Thread.Sleep(1000);
            Console.WriteLine("{0}執行緒終止",Thread.CurrentThread.Name);
            Console.ReadLine();
        }
    }
}



相關文章