29: }
30:
31: Thread.Sleep(5000);
32: }
33: }
好了,现在公司实体有了,老板就可以开始忙活了:
1: static void Main(string args)
2: {
3: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "WuDaokou", To = "LinDa Road", Fee = 500 });
4:
5: while (HouseMovingCompany.Instance.Contracts.Count > 0)
6: {
7: HouseMovingCompany.Instance.MoveHouse();
8: }
9: }
我们在前面设置了每次搬家耗时5秒钟,咱们把它想象成5个小时。嗯,一天接一个单子,还可以接受,但是随着老板生意日渐兴隆,有时候一天要接3个单子,这就最少要工作15个小时了,还要操心公司的运营等问题,的确忙不过来了,而且照这样算,老板一天不可能完成5个或5个以上的单子,严重制约了公司的发展:
1: static void Main(string args)
2: {
3: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "WuDaokou", To = "LinDa Road", Fee = 500 });
4: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiDan", To = "WangFujing", Fee = 1000 });
5: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiangShan", To = "The Forbidden City", Fee = 10000 });
6:
7: while (HouseMovingCompany.Instance.Contracts.Count > 0)
8: {
9: HouseMovingCompany.Instance.MoveHouse();
10: }
11: }
一天夜里,老板拖着疲倦的身子回到家里,一进门就一头倒在床上,他极力睁着快睁不开的眼睛,努力地对自己说:“不行,我一定要想个办法,不然我会被累死的!”。
其实办法很简单,谁都知道,招聘几个员工,再买几辆车,大家分头行动,不仅分担了工作负担,而且在规模扩大的同时还可以完成更多更大的单子。好,我们现在就借助多线程机制来实现我们的想法:
1: static void Main(string args)
2: {
3: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "WuDaokou", To = "LinDa Road", Fee = 500 });
4: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiDan", To = "WangFujing", Fee = 1000 });
5: HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiangShan", To = "The Forbidden City", Fee = 10000 });
6:
7: Thread thread = null;
8:
9: while (HouseMovingCompany.Instance.Contracts.Count > 0)
10: {
11: thread = new Thread(new ThreadStart(HouseMovingCompany.Instance.MoveHouse));
12:
13: thread.Start();
14: }
15: }
在这段程序中,我们分头行动,让每项搬家任务都由一个小团队去完成,结果我们发现,现在做三个单子的时间跟做一个单子的时间是一样的,提高了效率也扩大了公司规模。但是,既然引入了新的工作机制,我们在公司内部也不得不做一些小小的调整:
1: public void MoveHouse()
2: {
3: if (this.Contracts == null || this.Contracts.Count == 0)
4: {
5: return;
6: }
7:
8: Contract contract = null;
9:
10: lock (this.Contracts)
11: {
12: contract = this.Contracts[0];
13: