2 c# multithreading monitor thread-synchronization
这是我的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Writer {
public void Write(string xxx) { Console.Write(xxx); }
}
class Program
{
static Writer wrt;
static void Main(string[] args)
{
wrt = new Writer();
Thread trd = new Thread(new ThreadStart(delegate() {
lock (wrt)
{
Thread.Sleep(1000);
wrt.Write("1");
}
}));
trd.Start();
wrt.Write("0");
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
例外输出为"10",但输出为"01".为什么?
你需要锁定这两个地方:
wrt = new Writer();
Thread trd = new Thread(new ThreadStart(delegate() {
lock (wrt)
{
Thread.Sleep(1000);
wrt.Write("1");
}
}));
trd.Start();
lock(wrt) // Lock here, too
{
wrt.Write("0");
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
使用lock并不妨碍该实例被用于其他地方,它只是防止他人使用,直到你获得另一个锁定该实例lock完成.
将其lock视为"锁定对象",而不是将其视为对象是该锁定的唯一关键 - 没有其他人lock(yourObject)可以"解锁"该代码块,直到第一个完成.
请注意,这仍然可能会显示"01"作为输出,因为线程很可能不会足够快地启动以获得第lock一个,但这不是确定性的.