秒殺的簡單例子,實際應用中需要根據需求改進
using System; using System.Threading; class Program { static void Main() { // 創建一個秒殺商品對象 Product product = new Product("限時秒殺商品", 100); // 創建一個線程池,用於處理多線程秒殺請求 ThreadPool threadPool = new ThreadPool(10); // 模擬多個用戶同時發起秒殺請求 for (int i = 0; i < 100; i) { int userId = i; threadPool.Enqueue(() => { Console.WriteLine($"用戶{userId}發起秒殺請求"); if (product.Seckill(userId)) { Console.WriteLine($"用戶{userId}秒殺成功"); } else { Console.WriteLine($"用戶{userId}秒殺失敗,商品已售罄"); } }); } // 等待線程池中的所有任務完成 threadPool.WaitAll(); Console.WriteLine($"商品剩餘庫存:{product.Stock}"); } } class Product { private string name; private int stock; public Product(string name, int stock) { this.name = name; this.stock = stock; } public bool Seckill(int userId) { if (stock > 0) { stock--; Console.WriteLine($"用戶{userId}秒殺成功,商品剩餘庫存:{stock}"); return true; } else { Console.WriteLine($"用戶{userId}秒殺失敗,商品已售罄"); return false; } } }