多线程面试问题:顺序输出多个ABC序列,不使用Sleep。本来多线程是用来更高效的利用CPU的时间,所以执行的顺序是不太好控制的。这里不对这个问题的意义进行评述,说一下解决方案。参考了java的解决方案,主要方法就是指定下一个输出的字符,然后再输出的方法里边判断是不是当前字符就可以了。不知道有没有更好的方法。
先来看看代码吧:
public class ThreadDemo { public void ThreadStart() { MyLock myLock = new MyLock(); Thread th1 = new Thread(new ThreadStart((new PrintCalss("A", "B", myLock)).Print)); Thread th2 = new Thread(new ThreadStart((new PrintCalss("B", "C", myLock)).Print)); Thread th3 = new Thread(new ThreadStart((new PrintCalss("C", "A", myLock)).Print)); th1.Start(); th2.Start(); th3.Start(); myLock.CurrentStr = "A"; } } public class MyLock { public string CurrentStr { get; set; } } public class PrintCalss { MyLock myLock; public string CurrStr { get; set; } public string NextStr { get; set; } public PrintCalss(string currStr, string nextStr, MyLock curLock) { CurrStr = currStr; NextStr = nextStr; myLock = curLock; } public void Print() { int count = 10; while (count > 0) { if (myLock.CurrentStr != null && myLock.CurrentStr == CurrStr) { //从程序执行的的顺序分析,这个lock似乎意义不大了 lock (myLock) { Console.Write(myLock.CurrentStr); count--; myLock.CurrentStr = NextStr; } } } } }
根据上边的代码,又做了些简化:
public class ThreadDemo { string lockStr = string.Empty; string currStr = string.Empty; public void ThreadStart() { Thread th1 = new Thread(new ThreadStart(PrintA)); Thread th2 = new Thread(new ThreadStart(PrintB)); Thread th3 = new Thread(new ThreadStart(PrintC)); th1.Start(); th2.Start(); th3.Start(); lockStr = "A"; } public void PrintA() { int count = 10; while (count > 0) { if (Print("A")) count--; } } public void PrintB() { int count = 10; while (count > 0) { if (Print("B")) count--; ; } } public void PrintC() { int count = 10; while (count > 0) { if (Print("C")) count--; } } public bool Print(string printStr) { if (lockStr == printStr) { lock (this) { Console.Write(lockStr); lockStr = GetNextStr(); return true; } } return false; } public string GetNextStr() { if (lockStr == "A") { return "B"; } else if (lockStr == "B") { return "C"; } else if (lockStr == "C") { return "A"; } return string.Empty; } }
发表评论
相关文章
国内AI资源汇总,AI聊天、AI绘画、AI写作、AI视频、AI设计、AI编程、AI音乐等,国内顺畅访问,无需科学上网。
扫码或点击进入:萤火AI大全
文章分类
最新评论