题目一:两个线程交替打印0~100的奇偶数
这道题就是说有两个线程,一个名为偶数线程,一个名为奇数线程,偶数线程只打印偶数,奇数线程只打印奇数,两个线程按顺序交替打印。本文重点不是说的这道题,这道题是下面那道题的简单版本,用来做个过渡。
效果图:
此题核心点就是如何控制多线程的执行顺序,我们知道C#的System.Threading命名空间给开发者提供了控制线程相关的对象,线程同步常用对象有:Semaphore,ManualResetEvent,AutoResetEvent,这里我用AutoResetEvent来实现,代码如下:
public class ThreadExample { /// <summary> /// 两个线程交替打印0~100的奇偶数 /// </summary> public static void PrintOddEvenNumber() { var work = new TheadWorkTest(); var thread1 = new Thread(work.PrintOddNumer) { Name = "奇数线程" }; var thread2 = new Thread(work.PrintEvenNumber) { Name = "偶数线程" }; thread1.Start(); thread2.Start(); } } public class TheadWorkTest { private static readonly AutoResetEvent oddAre = new AutoResetEvent(false); private static readonly AutoResetEvent evenAre = new AutoResetEvent(false); public void PrintOddNumer() { oddAre.WaitOne(); for (var i = 0; i < 100; i++) { if (i % 2 != 1) continue; Console.WriteLine($"{Thread.CurrentThread.Name}:{i}"); evenAre.Set(); oddAre.WaitOne(); } } public void PrintEvenNumber() { for (var i = 0; i < 100; i++) { if (i % 2 != 0) continue; Console.WriteLine($"{Thread.CurrentThread.Name}:{i}"); oddAre.Set(); evenAre.WaitOne(); } } }