您好 ClarkChen,
>>希望某一次运行是thread1_a->thread2_a->thread1_b->thread2_b
这需要控制线程执行的顺序,我们需要在线程内部判断当前运行的是哪个线程,然后决定是空转等待还是继续执行,我写了个示例供你参考。
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(foo);
Thread t2 = new Thread(foo);
t1Id = t1.ManagedThreadId;
t2Id = t2.ManagedThreadId;
t1.Start();
t2.Start();
Console.Read();
}
static int t1Id;
static int t2Id;
static bool step1Ready = false;
static bool step2Ready = false;
static Barrier barrier = new Barrier(2);
static void foo()
{
if (System.Threading.Thread.CurrentThread.ManagedThreadId == t2Id)
{
while (true)
{
if (step1Ready == true)
{
break;
}
}
}
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "-- Statement1");
if (System.Threading.Thread.CurrentThread.ManagedThreadId == t1Id)
{
step1Ready = true;
}
barrier.SignalAndWait();
if (System.Threading.Thread.CurrentThread.ManagedThreadId == t2Id)
{
while (true)
{
if (step2Ready == true)
{
break;
}
}
}
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "-- Statement2");
if (System.Threading.Thread.CurrentThread.ManagedThreadId == t1Id)
{
step2Ready = true;
}
}
}
Best Regards,
Li Wang
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.