C# 暂停A线程执行B线程(Thread.Join方法)

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

namespace _5005_暂停A线程执行B线程_Thread.Join方法_
{
    class UsingJoin
    {
        //Thread.Join方法:阻塞调用线程,直到某个线程终止为止
        //Join(Int32) 阻塞调用线程,直或到某个线程终止经过了指定时间为止。  
        //Join(TimeSpan)  阻塞调用线程,直到某个线程终止或经过了指定时间为止。  
        Thread myThread1; Thread myThread2;
        public static void Main()
        {
            UsingJoin myUsingJoin = new UsingJoin();
            myUsingJoin.StartThread();
            Console.WriteLine(" 线程工作完成!!");
            Console.WriteLine(" 离开请按[ENTER] !!");
            Console.Read();
        }
        private void StartThread()
        {    //ThreadStart 委托 (System.Threading)
            myThread1 = new Thread(new ThreadStart(PrintNumber));
            myThread1.Name = "A Thread";
            myThread2 = new Thread(new ThreadStart(JoinPrintNumber));
            myThread2.Name = "B Thread";

            myThread1.Start();
            // myThread1.Join();
            myThread2.Start(); //启动线程
        }
        public void PrintNumber()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine
                  (Thread.CurrentThread.Name +
                  " 循环开始执行迄今第" + i + " 次");
                //每次执行暂停一秒,系统执行另外的线程,结果出现两个线程轮流输出结果
                // Thread.Sleep(1000);// 启动她后很有趣的现象
                //当循环判断等于5时,A Thread暂停线程,执行B Thread线程,B Thread结束后继续执行本线程A Thread
                if (i == 5)
                {
                    Console.WriteLine("暂停线程{0} ", Thread.CurrentThread.Name);
                    myThread1.Join();//myThread2被阻塞

                }
            }
        }
        public void JoinPrintNumber()
        {
            for (int i = 11; i < 30; i++)
            {
                Console.WriteLine
                  (Thread.CurrentThread.Name +
                  " 循环开始执行迄今第" + i + " 次");
                if (i == 30)
                {

                    Thread.CurrentThread.Abort();
                }
            }

        }
    }
}

 

你可能感兴趣的:(C#,后端)