我刚刚学习多线程,现在我正在尝试锁定功能,我在这里的代码中尝试的是每2秒显示myText
,但在控制台中它没有显示任何内容。
class Program
{
string Text = "";
long Counter = 0;
string Source = "abc def ghi";
static void Main(string[] args)
{
ThreadStart testThread1Start = new ThreadStart(new Program().WriteThread);
ThreadStart testThread2Start = new ThreadStart(new Program().ReadThread);
Thread[] testThread = new Thread[2];
testThread[0] = new Thread(testThread1Start);
testThread[1] = new Thread(testThread2Start);
foreach (Thread myThread in testThread)
{
myThread.Start();
}
Console.ReadLine();
}
public void WriteThread()
{
while (true)
{
Thread.Sleep(1000);
if (Source != null)
{
lock(this)
{
Text = Source;
Counter = Counter + 1;
}
}
}
}
public void ReadThread()
{
long myCounter = 0;
string myText = "";
while (true)
{
Thread.Sleep(1000);
if (myCounter < Counter)
{
lock (this)
{
myText = Text;
Console.WriteLine(myText);
}
}
}
}
}
ReadThread
中的计数器始终为0,为什么会这样?它仍然锁定或什么?