執行緒的阻塞

iamzxf發表於2015-05-25

當一個執行緒呼叫另一個執行緒時,在被呼叫的執行緒中呼叫join()方法,可以阻塞呼叫執行緒,直至某個執行緒終止時為止。

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

namespace Test
{
    class TestThread
    {
        private static void ThreadFuncOne()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name + "   i =  " + i);
            }
            Console.WriteLine(Thread.CurrentThread.Name + " has finished");
        }

        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "MainThread";

            Thread newThread = new Thread(new ThreadStart(TestThread.ThreadFuncOne));
            newThread.Name = "NewThread";

            for (int j = 0; j < 20; j++)
            {
                if (j == 10)
                {
                    newThread.Start();
                    newThread.Join();
                }
                else
                {
                    Console.WriteLine(Thread.CurrentThread.Name + "   j =  " + j);
                }
            }
            Console.Read();
        }
    }
}

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

namespace threadJoing2
{
    class SubThread
    {
        int number;
        public Thread workThrd;
        public SubThread(string name)
        {
            number = 0;
            workThrd = new Thread(this.working);
            workThrd.Name = name;
            workThrd.Start();
        }

        public void working()
        {
            Console.WriteLine("子執行緒{0}開始執行",workThrd.Name);
            while (number < 3)
            {
                Thread.Sleep(1000);
                Console.WriteLine("子執行緒:{0},現在數到{1}",workThrd.Name,number);
                number++;
            }
            Console.WriteLine("子執行緒{0}結束",workThrd.Name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主執行緒開始:");
            SubThread subT1 = new SubThread("subThreadOne");
            SubThread subT2 = new SubThread("subThreadTwo");
            SubThread subT3 = new SubThread("subThreadThree");

            subT1.workThrd.Join();
            subT2.workThrd.Join();
            subT3.workThrd.Join();

            Console.WriteLine("主執行緒結束");
            Console.ReadLine();
        }
    }
}


相關文章