C# 多线程

//----控制台程序代码

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

namespace duoxiancheng
{
class Program
{
static void Main(string[] args)
{
//HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "WuDaokou", To = "LinDa Road", Fee = 500 });
//HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiDan", To = "WangFujing", Fee = 1000 });
//HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "XiangShan", To = "The Forbidden City", Fee = 10000 });
//while (HouseMovingCompany.Instance.Contracts.Count > 0)
//{
// HouseMovingCompany.Instance.MoveHouse();
//}


HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "五道口", To = "林大道", Fee = 500 });
HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "西单", To = "王府井", Fee = 1000 });
HouseMovingCompany.Instance.Contracts.Add(new Contract { From = "香山", To = "故宫", Fee = 10000 });

Thread thread = null;

while (HouseMovingCompany.Instance.Contracts.Count > 0)
{
thread = new Thread(new ThreadStart(HouseMovingCompany.Instance.MoveHouse));

thread.Start();
}

Console.ReadLine();
}
}
}

//--Contract类

public class Contract
{
public string ID { get; private set; }
public string From { get; set; }
public string To { get; set; }
public decimal Fee { get; set; }

public Contract()
{
this.ID = Guid.NewGuid().ToString();
}
}

 

//---------HouseMovingCompany 类

public class HouseMovingCompany
{
private static HouseMovingCompany _instance = null;
public static HouseMovingCompany Instance
{
get { return (_instance == null ? _instance = new HouseMovingCompany() : _instance); }
}

public List<Contract> Contracts { get; private set; }

public HouseMovingCompany()
{
this.Contracts = new List<Contract>();
}

//public void MoveHouse()
//{
// if (this.Contracts == null || this.Contracts.Count == 0)
// {
// return;
// }

// Contract contract = 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);
// Console.WriteLine("时间:{2} 从 {0} 搬家至 {1}.", contract.From, contract.To, System.DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss.ffff"));

// }

// Thread.Sleep(5000);
//}


public void MoveHouse()
{
if (this.Contracts == null || this.Contracts.Count == 0)
{
return;
}

Contract contract = null;

lock (this.Contracts)
{
contract = this.Contracts[0];
this.Contracts.RemoveAt(0);
}

if (!String.IsNullOrEmpty(contract.From) && !String.IsNullOrEmpty(contract.To))
{
Console.WriteLine("时间:{2} 从 {0} 搬家至 {1}.", contract.From, contract.To, System.DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss.ffff"));


}

Thread.Sleep(5000);
}


}

posted @ 2014-12-30 15:29  秋香姑娘请你不要紧张  阅读(196)  评论(0编辑  收藏  举报