Thread with synchronization (2009-12-28)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestThreadConsole
{
static class MyShare
{
public static String name;
public static int couter = 1;
public static void WriteName()
{
Console.WriteLine(couter+". this call me >> " + MyShare.name);
couter++;
}
}
class MyObject
{
public string myName;
public void Start()
{
while (true)
{
Mutex objMutex = new Mutex(false, "ThreadLock");
try
{
objMutex.WaitOne();
MyShare.name = this.myName;
Console.WriteLine("I am >> " + this.myName);
MyShare.WriteName();
}finally{
objMutex.ReleaseMutex();
}
Random random = new Random();
Thread.Sleep(random.Next(1000, 3000));
}
}
}
class Program
{
static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.myName = "Chiwa";
Thread thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
obj = new MyObject();
obj.myName = "Pee";
thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
obj = new MyObject();
obj.myName = "Nok";
thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
obj = new MyObject();
obj.myName = "Kai";
thread = new Thread(new ThreadStart(obj.Start));
thread.Start();
}
}
}
|