模擬連接池
阿新 • • 發佈:2017-12-12
void 一個 同時 brush csharp tel nal readonly class
實例代碼:主要是lock防止池在同一時間被其它線程占用
//假設這個類型的對象創建起來比較耗時 public class TimeConsumeConnection { }
internal class Program { private static readonly object Sync = new object(); private static void Main(string[] args) { //假設一個池 TimeConsumeConnection[] conPool = new TimeConsumeConnection[100]; //聲明一個變量來維護當前池中的對象的個數。 int count = 0; //生產者,假設5個線程同時在進行“生產”→創建對象並加入到conPool池中 for (int i = 0; i < 5; i++) { //沒循環一次創建一個線程 Thread t = new Thread(() => { //不斷的生產對象並加入到conPool池中 while (true) { lock (Sync) { if (count < conPool.Length) { //創建一個Connection對象並把該對象加到conPool池中 TimeConsumeConnection connection = new TimeConsumeConnection(); conPool[count] = connection; count++; Console.WriteLine("生產了一個對象。"); } } Thread.Sleep(300); } }) { IsBackground = true }; t.Start(); } //消費者假設有10個消費者,從池中獲取對象並使用 for (int i = 0; i < 10; i++) { Thread t = new Thread(() => { while (true) { lock (Sync) { //在消費對象前,要判斷一下池中是否有可用對象 if (count > 0) { TimeConsumeConnection con = conPool[count - 1]; Console.WriteLine("使用該對象:" + con); conPool[count - 1] = null; count--; } } Thread.Sleep(50); } }) { IsBackground = true }; t.Start(); } Console.ReadKey(); } }
模擬連接池