您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#多線程練習題分析”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#多線程練習題分析”吧!
題目:模擬生產、入庫、銷售(50分)
假設某企業自產、自存、自銷,需要將工廠生產的各類產品不定時的運到倉庫,與此同時,需要將倉庫中的貨物運往超市和商場中進行銷售,請編寫一個程序模擬此過程(主要是存取這個過程)。
評分標準:
1. 倉庫的存量是固定的,可以假設為一個常量,比如10。(5分)
2. 倉庫滿的時候,不能再向倉庫中存貨。(10分)
3. 倉庫空的時候,不能賣出貨物。(10分)
4. 存貨和取貨是同時進行的,不要出現先存滿再取完貨再存滿再取完的效果或者存一個取一個再存再取這樣的效果。(15分)
5. 思路清晰,輸出工整,編碼規范,有正確的異常處理。(10分)
用多線程模擬倉庫存儲和銷售的過程代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.IO; namespace MultiThreadStore { class Program { //入口 static void Main(string[] args) { Goods goods = new Goods(); Thread storeGoods = new Thread(new ParameterizedThreadStart(store)); Thread sellGoods = new Thread(new ParameterizedThreadStart(sell)); storeGoods.Start(goods); sellGoods.Start(goods); Console.ReadLine(); } //存貨方法 private static void store(object obj) { bool storeFlag = true; Random random = new Random(); while (storeFlag) { try { Goods goods = obj as Goods; if (goods.Num < goods.MaxNum) { goods.Num++; Console.WriteLine("Store a goods, " + goods.Num + " goods left!"); } else { Console.WriteLine("The store is full now."); } Thread.Sleep(random.Next(500, 1000)); } catch (Exception ex) { WriteLog(ex); storeFlag = false; } } } //賣貨方法 public static void sell(object obj) { bool sellFlag = true; Random random = new Random(); while (sellFlag) { try { Goods goods = obj as Goods; if (goods.Num > 0) { goods.Num--; Console.WriteLine("Sell a goods, " + goods.Num + " goods left!"); } else { Console.WriteLine("There are no goods now."); } Thread.Sleep(random.Next(1000, 4000)); } catch (Exception ex) { WriteLog(ex); sellFlag = false; } } } //打log方法 private static void WriteLog(Exception ex) { string logUrl = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\MuliThreadStorelog.txt"; if (File.Exists(@logUrl)) { using (FileStream fs = new FileStream(logUrl, FileMode.Append)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { try { sw.Write(ex); } catch (Exception ex1) { WriteLog(ex1); } finally { sw.Close(); fs.Close(); } } } } else { using (FileStream fs = new FileStream(logUrl, FileMode.CreateNew)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { try { sw.Write(ex); } catch (Exception ex1) { WriteLog(ex1); } finally { sw.Close(); fs.Close(); } } } } } } //貨品類 class Goods { public int Num { get; set; } public int MaxNum { get; set; } public Goods() { Num = 10; MaxNum = 50; } } }
運行截圖:
感謝各位的閱讀,以上就是“C#多線程練習題分析”的內容了,經過本文的學習后,相信大家對C#多線程練習題分析這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。