您的位置:首页 > 其它

多线程操作的例子

2011-02-22 14:38 204 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: