Singleton
来源:互联网 发布:阿里云ssh连接不上 编辑:程序博客网 时间:2024/05/01 16:39
Singleton是我学的第一个模式,看了博客园上的解释,有点小问题。改了之后贴上。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Singleton
{
public class CountSigleton
{
/**////存储唯一的实例
static CountSigleton uniCounter = new CountSigleton();
/**////存储计数值
private int totNum = 0;
private CountSigleton()
{
/**////线程延迟2000毫秒
Thread.Sleep(2000);
}
static public CountSigleton Instance()
{
return uniCounter;
}
/**////计数加1
public void Add()
{
totNum ++;
}
/**////获得当前计数值
public int GetCounter()
{
return totNum;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Singleton
{
public class CountMutilThread
{
public CountMutilThread()
{
}
/**//// <summary>
/// 线程工作
/// </summary>
public static void DoSomeWork()
{
/**////构造显示字符串
string results = "";
/**////创建一个Sigleton实例
CountSigleton MyCounter = CountSigleton.Instance();
/**////循环调用四次
for(int i=1;i<5;i++)
{
/**////开始计数
lock (MyCounter)
{
MyCounter.Add();
results += "线程";
results += Thread.CurrentThread.Name.ToString() + "——〉";
results += "当前的计数:";
results += MyCounter.GetCounter().ToString();
results += "/n";
Console.WriteLine(results);
/**/
///清空显示字符串
results = "";
}
}
}
public void StartMain()
{
Thread thread0 = Thread.CurrentThread;
thread0.Name = "Thread 0";
Thread thread1 =new Thread(new ThreadStart(DoSomeWork));
thread1.Name = "Thread 1";
Thread thread2 =new Thread(new ThreadStart(DoSomeWork));
thread2.Name = "Thread 2";
Thread thread3 =new Thread(new ThreadStart(DoSomeWork));
thread3.Name = "Thread 3";
thread1.Start();
thread2.Start();
thread3.Start();
/**////线程0也只执行和其他线程相同的工作
DoSomeWork();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Singleton
{
public class CountClient
{
public static void Main(string[] args)
{
CountMutilThread cmt = new CountMutilThread();
cmt.StartMain();
Console.ReadLine();
}
}
}
- Singleton
- Singleton
- singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- singleton
- Singleton
- Singleton
- Singleton
- Singleton
- Singleton
- 逆向最长匹配算法的实现
- 巨形水母“入侵”日本:身怀毒素成群结队(图)
- NetBeans 时事通讯(刊号 # 60 - Jun 21, 2009)
- telnet远程登录乱码问题
- getAttribute和getParameter的区别
- Singleton
- FLEX实践—自创相册
- 2009福布斯最具潜力中小企业榜
- ContentProvider数据模型概述
- 基于正向最大匹配法的Lucene分词器
- 十种已问世的未来材料:隐形与隐声成为可能
- 基于既定词表的自适应汉语分词技术研究
- *蛋购物上当经历
- 2008年Linux的25个顶级游戏