Here’s a little question about Threading – this would be a great interview question, in my opinion!
Given the code below:
public class Producer
{
[ThreadStatic]
readonly static private Producer _instance = new Producer();
static private int _instanceCount;
readonly private int _instanceId;
private Producer()
{
_instanceId = ++_instanceCount;
}
static public Producer Instance
{
get { return _instance; }
}
public string Name
{
get
{
return String.Format("Instance {0} of {1}",
_instanceId, _instanceCount);
}
}
}
public class Consumer
{
public Consumer()
{
Thread t1 = new Thread(IdentifyProducer);
t1.Start();
Thread t2 = new Thread(IdentifyProducer);
t2.Start();
t1.Join();
t2.Join();
}
public void IdentifyProducer()
{
Console.WriteLine(Producer.Instance.Name);
}
}
What will happen when you create a new instance of the Consumer class?

