Thread(C#)

nonamedemo發表於2007-11-01

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace RailWayStation
{
class Program
{
static void Main(string[] args)
{
Station NewYorkCity = new Station();
Thread t1=new Thread(new ThreadStart(NewYorkCity.SellTicket));//新例項化了個執行緒的物件然後再new了個執行緒開始,再把方法加進去
Thread t2=new Thread(new ThreadStart(NewYorkCity.SellTicket));
Thread t3 = new Thread(new ThreadStart(NewYorkCity.SellTicket));
t1.Name = "1號視窗";
t2.Name = "2號視窗";
t3.Name = "3號視窗";

t1.Start();
t2.Start();
t3.Start();


}
}
class Station
{
int ticket = 100;//火車站有?張票
public void SellTicket()
{
while (true)
{
lock (this)
{
if (ticket > 0)
{
Console.WriteLine(Thread.CurrentThread.Name + "第" + ticket.ToString() + "張票");
ticket--;
}
else { break; }
}
}


}
}
}

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10395457/viewspace-980397/,如需轉載,請註明出處,否則將追究法律責任。

相關文章