2010-8-19,做了个多线程的案例。有单件模式的多线程(方法:InstanceSingleTon)和计数的多线程(方法:Count)。
代码比较简单,主要是code单件模式,多线程同步,异步的概念。
贴代码如下:
class Program
{
static void Main(string[] args)
{
{
static void Main(string[] args)
{
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread(new ThreadStart(SingleTon.Count));
}
{
threads[i] = new Thread(new ThreadStart(SingleTon.Count));
}
foreach (Thread t in threads)
{
t.Start();
}
{
t.Start();
}
Console.ReadLine();
}
}
}
}
public class SingleTon
{
static int intIn = 0;
public static SingleTon instance;
private static object lockHelper = new object();
private static object lockHelper = new object();
private SingleTon()
{
}
{
}
/// <summary>
/// 计数。注释的lock代码是锁对象,实现多线程-同步操作。目的:按顺序显示索引值。1,2,3,4,5,6,7,8,9,10
/// 计数。注释的lock代码是锁对象,实现多线程-同步操作。目的:按顺序显示索引值。1,2,3,4,5,6,7,8,9,10
/// 现在的代码是多线程-异步操作。
/// </summary>
public static void Count()
{
//lock (lockHelper)
//{
// Console.WriteLine("Current:" + Convert.ToString(++intIn));
//}
/// </summary>
public static void Count()
{
//lock (lockHelper)
//{
// Console.WriteLine("Current:" + Convert.ToString(++intIn));
//}
Console.WriteLine("Current:" + Convert.ToString(++intIn));
}
}
/// <summary>
/// 单件模式,防止多线程-同步实例化
/// </summary>
/// <returns></returns>
public static SingleTon InstanceSingleTon()
{
if (instance == null)
{
lock (lockHelper)
{
if (instance==null)
{
instance = new SingleTon();
}
}
}
return instance;
}
}
/// 单件模式,防止多线程-同步实例化
/// </summary>
/// <returns></returns>
public static SingleTon InstanceSingleTon()
{
if (instance == null)
{
lock (lockHelper)
{
if (instance==null)
{
instance = new SingleTon();
}
}
}
return instance;
}
}