Ejemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            // 还是先清理一下输出好了
            Console.Clear();

            // 初始化数组
            var customers = new[]
            {
                "甲", "乙", "丙"
            };

            _isDone        = new bool[customers.Length];
            _maxScoreFoods = new AbstractFood[customers.Length];
            _maxScores     = new int[customers.Length];
            for (int i = 0; i < _maxScores.Length; i++)
            {
                _maxScores[i] = -1;
            }

            var menu      = OrderSystem.Menu.Instance;
            var menuItems = menu.Items;

            var foodFactory = new FoodFactory();

            for (int i = 0; i < customers.Length; i++)
            {
                var index  = i;
                var name   = customers[index];
                var thread = new Thread(() =>
                {
                    // 点 5 个菜
                    for (int j = 0; j < 5; j++)
                    {
                        var id       = _rand.Next(menuItems.Length);
                        var menuItem = menuItems[id];

                        var food = foodFactory.CreateById(menuItem.Id);
                        lock (_forLock)
                        {
                            Console.Write(name + "吃了" + menuItem.Name + " ");
                            food.Show();
                            var foodScore = food.Score();

                            if (foodScore > _maxScores[index])
                            {
                                _maxScores[index]     = foodScore;
                                _maxScoreFoods[index] = food;
                            }

                            Console.WriteLine("评分是:" + foodScore);
                        }

                        // 吃完这个菜等个 500 ~ 3000 毫秒休息下吧。
                        Thread.Sleep(_rand.Next(500, 3001));
                    }
                    _isDone[index] = true;

                    lock (_forLock)
                    {
                        var foregroundColor     = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(name + "吃完了");
                        Console.Write(",最高分是:");
                        Console.Write(_maxScores[index] + "," + _maxScoreFoods[index].GetType().Name);
                        Console.WriteLine();
                        Console.ForegroundColor = foregroundColor;
                    }

                    DoFinalOutput();
                })
                {
                    IsBackground = true
                };
                thread.Start();
            }
        }