volidatile关键字
/volidatile关键字的使用,动手便代码实例操作
class SchoolBus
{
volatile private bool isAlive;//关键字volatile表明该变量是活动的,确保在每一个线程在访问isAlive在每一个时刻都能得到最新的值
public SchoolBus(bool isAlive)
{
this.isAlive = isAlive;
}
public void Start()
{
Console.Write("The school bus is starting...");
Thread.Sleep(3000);
Running();
}
public void Running()
{
while (isAlive)
{
Thread.Sleep(100);
Console.WriteLine("The school bus is walking......");
}
if (isAlive == false)
Console.WriteLine("OK,MainThread,You can run!I am stopping!!");
}
public void Stop(bool b)
{
this.isAlive = b;
}
}
class BusManager
{
public static void Main(string[] args)
{
SchoolBus bus = new SchoolBus(true);
ThreadStart start = new ThreadStart(bus.Start);
Thread t = new Thread(start);
t.Start();//线程启动
while (!t.IsAlive) ;
//Console.WriteLine("The School Bus starts to run!!!");
Thread.Sleep(6000);//暂停主线程,确保辅助线程能够运行一段时间
bus.Stop(false);
//Thread.Sleep(2000);//确保辅助线程完成任务
t.Join();//确保辅助线程完全结束之后,主线程才能执行下去
Console.WriteLine("The School Bus is stopping...");
Console.WriteLine(t.ThreadState.ToString());//输出stopped
if (t.ThreadState == ThreadState.Stopped)
Console.WriteLine("The assitant thread is stopped!");
//string str = null;
//string strName = string.Empty;
//if (strName=="")
//{
// Console.WriteLine("Equal");//输出Equal;
//}
Console.Read();
}
}