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;
- }
- }
- }
運行截圖:
責任編輯:王雪燕
來源:
博客園