5、多线程-按顺序调用,A->B->C,AA 打印 5 次,BB 打印10 次,CC 打印 15 次,重复 10 次

题目

多线程按顺序调用,A->B->C,AA 打印 5 次,BB 打印10 次,CC 打印 15 次,重复 10 次

代码示例

using System;
using System.Threading;
using System.Threading.Tasks;

public class ABCPrinter
{
	private int repeatCount;
	private int aPrintCount;
	private int bPrintCount;
	private int cPrintCount;

	private AutoResetEvent aEvent = new AutoResetEvent(true); // 一开始 A 可以运行
	private AutoResetEvent bEvent = new AutoResetEvent(false);
	private AutoResetEvent cEvent = new AutoResetEvent(false);

	public ABCPrinter(int repeatCount)
	{
		this.repeatCount = repeatCount;
		this.aPrintCount = 5;
		this.bPrintCount = 10;
		this.cPrintCount = 15;
	}

	public void PrintA(Action<string> printChar)
	{
		for (int i = 0; i < repeatCount; i++)
		{
			for (int j = 0; j < aPrintCount; j++)
			{
				aEvent.WaitOne(); // 等待 A 事件
				printChar("A"); // 打印 A
				bEvent.Set(); // 唤醒 B 线程
			}
		}
	}

	public void PrintB(Action<string> printChar)
	{
		for (int i = 0; i < repeatCount; i++)
		{
			for (int j = 0; j < bPrintCount; j++)
			{
				bEvent.WaitOne(); // 等待 B 事件
				printChar("B"); // 打印 B
				cEvent.Set(); // 唤醒 C 线程
			}
		}
	}

	public void PrintC(Action<string> printChar)
	{
		for (int i = 0; i < repeatCount; i++)
		{
			for (int j = 0; j < cPrintCount; j++)
			{
				cEvent.WaitOne(); // 等待 C 事件
				printChar("C"); // 打印 C
				if (j == cPrintCount - 1)
				{
					aEvent.Set(); // 最后一个 C 的时候唤醒 A 线程
				}
				else
				{
					cEvent.Set(); // 继续唤醒 C 线程
				}
			}
		}
	}

	public static void Main(string[] args)
	{
		int repeatCount = 10;
		ABCPrinter abcPrinter = new ABCPrinter(repeatCount);

		var aTask = Task.Run(() => abcPrinter.PrintA(Console.Write));
		var bTask = Task.Run(() => abcPrinter.PrintB(Console.Write));
		var cTask = Task.Run(() => abcPrinter.PrintC(Console.Write));

		Task.WaitAll(aTask, bTask, cTask);
		Console.WriteLine();
	}
}
posted @ 2024-12-14 11:33  似梦亦非梦  阅读(11)  评论(0编辑  收藏  举报