有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC

rt, C# codes as below:

 

using System;
using System.Threading;
namespace MConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintHelper.MaxCycle = 30;
            Thread thread1 = new Thread(new ThreadStart(PrintHelper.Print)) { Name = "A" };
            Thread thread2 = new Thread(new ThreadStart(PrintHelper.Print)) { Name = "B" };
            Thread thread3 = new Thread(new ThreadStart(PrintHelper.Print)) { Name = "C" };
            thread1.Start();
            thread2.Start();
            thread3.Start();
 
            Console.ReadKey();
        }
    }
    class PrintHelper
    {
        /// <summary>
        /// Help current thread keep in touch with other threads.
        /// </summary>
        private static int counter;
        /// <summary>
        /// Define the exit of method cycle.
        /// </summary>
        public static int MaxCycle { get; set; }
        public static void Print()
        {
            while (counter < MaxCycle)
            {
                string name = Thread.CurrentThread.Name;
                if ((counter % 3 == 0 && name == "A") || (counter % 3 == 1 && name == "B") || (counter % 3 == 2 && name == "C"))
                {
                    lock ("lock this Code!")
                    {                     
                        if (counter < MaxCycle)
                        {
                            Console.Write(name);
                            counter++;
                        }
                    }
                }
            }
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值