lijinchang

导航

多线程操作的例子

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication5
{
    public class Contract
    {
        private string id;
        private string from;
        private string to;
        private decimal fee;
        public string ID { get { return id; } private set { id = value; } }
        public string From { get { return from; } set { from = value; } }
        public string To { get { return to; } set { to = value; } }
        public decimal Fee { get { return fee; } set { fee = value; } }
        public Contract(string from,string to,decimal fee)
        {
            this.From=from;
            this.To=to;
            this.Fee=fee;
            this.ID = DateTime.Now.ToBinary().ToString().Replace("-", String.Empty);
        }
    }
    public class HouseMovingCompany 
    { 
        private static HouseMovingCompany _instance = null; 
        public static HouseMovingCompany Instance 
        {  
            get { return (_instance == null ? _instance = new HouseMovingCompany() : _instance); } 
        }
        private List<Contract> cc;
        public List<Contract> Contracts
        {
            get { return cc; }
            private set{cc=value;} }
        public HouseMovingCompany() 
        { 
            this.Contracts = new List<Contract>();
        } 
        public void MoveHouse() 
        {
            if (this.Contracts == null || this.Contracts.Count == 0)
            {
                return;
            }
            Contract contract;
            lock (Contracts)
            {
                 contract = this.Contracts[0];
            }
            this.Contracts.RemoveAt(0); 
            if (!String.IsNullOrEmpty(contract.From) && !String.IsNullOrEmpty(contract.To)) 
            { 
                Console.WriteLine("Move the house from {0} to {1}.", contract.From, contract.To);
            } 
            Thread.Sleep(5000); 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           // Contract cc=new Contract();

            HouseMovingCompany.Instance.Contracts.Add(new Contract ("WuDaokou", "LinDa Road", 500 ));
            HouseMovingCompany.Instance.Contracts.Add(new Contract ("XiDan",  "WangFujing",1000 ));
            HouseMovingCompany.Instance.Contracts.Add(new Contract ("XiangShan",  "The Forbidden City", 10000 )); 
            Thread thread = null;
            while (HouseMovingCompany.Instance.Contracts.Count > 0) 
            { 
                thread = new Thread(new ThreadStart(HouseMovingCompany.Instance.MoveHouse)); 
                thread.Start(); 
            }
            Console.Read();
        }
    }
}

posted on 2011-02-22 14:38  lijinchang  阅读(164)  评论(0编辑  收藏  举报