You need to lock in both places:
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();
Using a lock
doesn't prevent that instance from being used other places, it just prevents that instance from being used to acquire another lock until your lock
is done.
Instead of thinking of lock
as "locking the object", think of it as your object is the one and only key for that lock - no other lock(yourObject)
can "unlock" that block of code until the first one is done.
Note that this will still likely show "01" as output, as it's very unlikely that the thread will startup quickly enough to get the lock
first, but that's not deterministic.