当前位置: 首页 > 科技观察

说说Thread线程的常用操作

时间:2023-03-18 14:47:48 科技观察

本文转载自微信公众号《UP科技控》,作者conan5566。转载本文请联系UP技控公众号。创建线程线程是通过扩展Thread类创建的。扩展的Thread类调用Start()方法来启动子线程的执行。下面的程序演示了这个概念:ThreadchildThread=newThread(childref);childThread.Start();Console.ReadKey();}}以上代码编译执行后,会产生如下结果:方法。下面的示例演示了使用sleep()方法在特定时间挂起线程。classThreadCreationProgram{publicstaticvoidCallToChildThread(){Console.WriteLine("Childthreadstarts");//线程暂停5000毫秒intsleepfor=5000;Console.WriteLine("ChildThreadPausedfor{0}seconds",sleepfor/1000);Thread.Sleep(sleepfor);控制台.WriteLine("Childthreadresumes");}staticvoidMain(string[]args){ThreadStartchildref=newThreadStart(CallToChildThread);Console.WriteLine("InMain:CreatingtheChildthread");ThreadchildThread=newThread(childref);childThread.Start();安慰。ReadKey();}}以上代码编译执行后,会产生如下结果:InMain:CreatingtheChildthreadChildthreadstartsChildThreadPausedfor5secondsChildthreadresumesDestroythethreadAbort()方法用于销毁线程。通过抛出threadabortexception在运行时中止线程。无法捕获此异常。如果有finally块,控制将被发送到finally块。下面的程序说明了这一点:classThreadCreationProgram{publicstaticvoidCallToChildThread(){try{Console.WriteLine("Childthreadstarts");//计数到10for(intcounter=0;counter<=10;counter++){Thread.Sleep(500);Console.WriteLine(counter);}Console.WriteLine("ChildThreadCompleted");}catch(ThreadAbortExceptione){Console.WriteLine("ThreadAbortException");}最后{Console.WriteLine("Couldn'tcatchtheThreadException");}}staticvoidMain(string[]args){ThreadStartchildref=newThreadStart(CallToChildThread);Console.WriteLine("InMain:CreatingtheChildthread");ThreadchildThread=newThread(childref);childThread.Start();//暂时停止主线程Thread.Sleep(2000);//AbortchildthreadnowConsole.WriteLine("InMain:AbortingtheChildthread");childThread.Abort();Console.ReadKey();}}上面的代码编译执行后,产生结果如下:InMain:CreatingtheChildthreadChildthreadstarts012InMain:AbortingtheChildthreadThreadAbortExceptionCouldn'tcatchtheThreadException