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#中一道关于多线程的基础练习题——模拟仓库存销过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows7 连接Windows S
- 下一篇: 太相信书的人,格局不会太大