多线程之搬运货物1:分堆搬

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> productList = new List<string>() {"AAAA","BBBB","CCCC","DDDD","EEEE" };//货物
            MoveHelper moveHelper = new MoveHelper();

            //两个人或多个人时
            int personCount = 6;
            Dictionary<string, List<string>> person_Product = new Dictionary<string, List<string>>();//人与货物的对应表
            
//给人分配任务
            while (productList.Count > 0)
            {
                for (int i = 0; i < personCount; i++)
                {
                    if (productList.Count <= 0break;
                    string key = "P" + (i+1).ToString();
                    List<string> plist=new List<string>();
                    if (!person_Product.Keys.Contains(key))
                        person_Product.Add(key, plist);
                    else plist = person_Product[key];
                    plist.Add(productList[0]);
                    productList.RemoveAt(0);
                }
            }
            //有多个人就创建多个个线程
            foreach (string str in person_Product.Keys)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(moveHelper.MoveThings));
                MoveParameters ps = new MoveParameters(str, person_Product[str]);
                thread.Start(ps);
                //thread.Join();//当加上join后,所用时间是单线程的时间。并不会少时间。
            }

            Console.WriteLine("ddddddddddddddddddddddddddddddddddd");
            Console.ReadLine();
        }
    }

    public class MoveHelper
    {
        public void MoveThings(object product)
        {
            MoveParameters ps = product as MoveParameters;

            if (ps.Products != null && ps.Products.Count > 0)
            {
                foreach (string pro in ps.Products)
                {
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("货物" + pro + "已经被" + ps.PersonName + "成功送达目的地!" + System.DateTime.Now.ToString());//YYYY-MM-DD HH-MM-mm
                }
            }
        }
    }

    public class MoveParameters
    {
        public string PersonName { getset; }
        public List<string> Products { getset; }

        public MoveParameters() { }

        public MoveParameters(string personName, List<string> products)
        {
            this.PersonName = personName;
            this.Products = products;
        }
    }
}
posted @ 2014-01-15 15:32  pnljs  阅读(579)  评论(0编辑  收藏  举报