Created
October 26, 2012 05:43
-
-
Save JeffreyZhao/3957082 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The code below would print overlapped A and B sequences like: | |
// ... | |
// A | |
// A | |
// B | |
// B | |
// ... | |
// | |
// Please add multi-threading protection code to make sure that | |
// As and Bs are printed in the order of: | |
// ... | |
// A | |
// B | |
// A | |
// B | |
// ... | |
static void PrintA() | |
{ | |
Console.WriteLine("A"); | |
} | |
static void PrintB() | |
{ | |
Console.WriteLine("B"); | |
} | |
// DO NOT touch the code below | |
for (var i = 0; i < 10; i++) | |
{ | |
new Thread(() => { | |
while (true) { | |
PrintA(); | |
PrintB(); | |
} | |
}).Start(); | |
} |
haijunxiong
commented
Oct 26, 2012
private readonly static object lockerA = new object();
private readonly static object lockerB = new object();
static void PrintA()
{
lock(lockerA)
{
Console.WriteLine("A");
}
}
static void PrintB()
{
lock(lockerB)
{
Console.WriteLine("B");
}
}
// DO NOT touch the code below
for (var i = 0; i < 10; i++)
{
new Thread(() => {
while (true) {
PrintA();
PrintB();
}
}).Start();
}
//俩ThreadStart 把俩方法委托进去
ThreadStart tsA = new ThreadStart(PrintA);
ThreadStart tsB = new ThreadStart(PrintB);
//俩委托调用. acB = null 是因为不赋值后面报未赋值错误.
AsyncCallback acA, acB = null;
//PrintA结束委托后,再调用tsB
acA = new AsyncCallback(delegate(IAsyncResult r)
{
tsA.EndInvoke(r);
Thread.Sleep(37);
tsB.BeginInvoke(acB, null);
});
//PrintB结束委托后,再调用tsA,写成个套套.
acB = new AsyncCallback(delegate(IAsyncResult r)
{
tsB.EndInvoke(r);
Thread.Sleep(51);
tsA.BeginInvoke(acA, null);
});
//然后就开始死磕
tsA.BeginInvoke(acA, null);
//以下是干扰代码 用于测试
new Thread(delegate() {
while (true)
{
Thread.Sleep(521);
Console.Write("-");
}
}).Start();
//主线程的干扰
while (true)
{
Thread.Sleep(795);
Console.Write("=");
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment