一个最简单的线程问题
public class Alpha
{
public void Beta()
{
while (true)
{
Console.WriteLine("Alpha.Beta is running in its own thread.");
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Thread Start/Stop/Join Sample");
Alpha oAlpha = new Alpha();
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
oThread.Start();
while (!oThread.IsAlive)
Thread.Sleep(1);
oThread.Suspend(); -----------------(1)挂起线程
oThread.Join(); -----------------(2)这是干什么? 不懂,希望能有高人解释。
oThread.Resume(); -----------------(3)恢复现程,如果把这句话省略,程序不直停在这里,不能向下走,为什么??
Console.WriteLine("Alpha.Beta has finished");
try
{
Console.WriteLine("Try to restart the Alpha.Beta thread");
oThread.Resume(); -----------------(4)恢复现程,本来是想把(3)那里删除,在这里恢复线程,可是如果(3)那里取消,根本进不到这里来,为什么??
}
catch (ThreadStateException)
{
Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
Console.WriteLine("Expected since aborted threads cannot be restarted.");
Console.ReadLine();
}
}
}
[解决办法]
oThread.Join(); 在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止
Main函数执行到这的时候不会继续执行下一条语句,会等到oThread线程执行结束,Main才继续执行。
因为有oThread.Join();的存在,而且你线程函数是死循环不退出,所以后面的代码都不执行。
Thread.Sleep(1);将当前线程挂起指定的时间
单位1毫秒 不是1秒
但是这个时间是不准确的,Thread.Sleep(1);之后的语句执行时,时间差不一定是1毫秒,因为CPU轮询时间片是20毫秒左右,这个时间本身就不固定,也看系统当前的线程调度情况。如果没有把CPU分配给别的线程,那有1毫秒之后继续执行的可能。
[解决办法]
public void Beta() { while (true) { Console.WriteLine("Alpha.Beta is running in its own thread."); } }
[解决办法]
[解决办法]
static void Main(string[] args) { Console.WriteLine("Thread Start/Stop/Join Sample"); Alpha oAlpha = new Alpha(); Thread oThread = new Thread(new ThreadStart(oAlpha.Beta)); oThread.Start(); while (!(oThread.ThreadState== ThreadState.Running )) Thread.Sleep(1); oThread.Suspend();// -----------------(1)挂起线程 Console.WriteLine(@"Alpha.Beta has finished\r\n"); try { Console.WriteLine(@"Try to restart the Alpha.Beta thread\r\n"); oThread.Resume(); } catch (ThreadStateException) { Console.Write("ThreadStateException trying to restart Alpha.Beta. "); Console.WriteLine("Expected since aborted threads cannot be restarted."); Console.ReadLine(); } Console.ReadKey(); } public class Alpha { public void Beta() { while (true) { Console.WriteLine("Alpha.Beta is running in its own thread."); Thread.Sleep(1); } } }
[解决办法]
你一DEBUG就输了,
DEBUG就是单线程,当然我也没有更好的方法,要具体分析到底当前断点到底是哪个线程
实际运行中线程是同时跑的,和DEBUG有些出入。
现在没时间,晚上再研究研究