所以我有这个程序试图在两个不同的线程 thread1 和 thread2 之间建立通信。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Project1
{
class Class1
{
public static void thread1()
{
Console.WriteLine("1");
Console.WriteLine("t2 has printed 1, so we now print 2");
Console.WriteLine("t2 has printed 2, so we now print 3");
}
public static void thread2()
{
Console.WriteLine("t1 has printed 1, so we now print 1");
Console.WriteLine("t1 has printed 2, so we now print 2");
Console.WriteLine("t1 has printed 3, so we now print 3");
}
public static void Main() {
Thread t1 = new Thread(new ThreadStart(() => thread1()));
Thread t2 = new Thread(new ThreadStart(() => thread2()));
t1.Start();
t2.Start();
t2.Join();
t1.Join();
}
}
}
但是,我希望它发生这样的行:
Console.WriteLine("1");
...首先被执行,而 thread2 只是等待这一行被执行。然后只有这样它才会打印:
Console.WriteLine("t1 has printed 1, so we now print 1");
打印完这一行之后,只有这样,这一行才会:
Console.WriteLine("t2 has printed 1, so we now print 2");
...打印出来,等等。所以我想更改代码,以便线程相互通信,以便按以下顺序打印行:
Console.WriteLine("1"); // from t1
Console.WriteLine("t1 has printed 1, so we now print 1"); // from t2
Console.WriteLine("t2 has printed 1, so we now print 2"); // from t1
Console.WriteLine("t1 has printed 2, so we now print 2"); // from t2
Console.WriteLine("t2 has printed 2, so we now print 3"); // from t1
Console.WriteLine("t1 has printed 3, so we now print 3"); // from t2
我了解 lock 的作用,但它仅适用于两个不同的线程在同一个函数上运行的情况。但是,在这里,这两个功能是不同的,因此我不能在这里使用 lock。
有任何想法吗?