using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CountClient { public class CountSigleton { static CountSigleton uniCounter = null; private int totNum = 0; private CountSigleton() { Thread.Sleep(2000); } public static CountSigleton Instance { get { if (uniCounter==null) { uniCounter=new CountSigleton(); } return uniCounter; } } 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 CountClient { public class CountMutilThread { public CountMutilThread(){ } public static void DoSomeWork() { string results = ""; CountSigleton MyCounter = CountSigleton.Instance; for (int i = 1; i < 5; i++) { 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 CountClient { class Program { static void Main(string[] args) { CountMutilThread cmt = new CountMutilThread(); cmt.StartMain(); Console.ReadLine(); } } }
单件模式,例子。
保证一个类仅有一个实例
参考:http://terrylee.cnblogs.com/archive/2005/12/09/293509.html
浙公网安备 33010602011771号