一个多线程的windows控制台应用程序
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一个多线程的windows控制台应用程序
一、要求:
编写一个单进程、多线程的windows控制台应用程序。
二、平台:
Window XP
C#
三、内容:
每个进程都有分配给它的一个或多个线程。线程是一个程序的执行部分。
操作系统把极短的一段时间轮流分配给多个线程。时间段的长度依赖于操作系统和处理器。
每个进程都开始一个默认的线程,但是能从它的线程池中创建一个新的线程。
线程是允许进行并行计算的一个抽象概念:在一个线程完成计算任务的同时,另一个线程可以对图像进行更新,两个线程可同时处理同一个进程发出的两个网络请求。
如图所示,选择操作:
1、创建和启动一个线程。在一个进程中同时教和运行两个线程,并且可以不需要停止或者释放一个线程。
相关代码及其解释:
public class Threading1:Object
{
public static void startup()
{
//创建一个线程数组
Thread[] threads=new Thread[2];
for(int count=0;count { //创建线程 threads[count]=new Thread(new ThreadStart(Count)); //启动线程 threads[count].Start(); } public static void Count() { for(int count=1;count<=9;count++) Console.Write(count+" "); } } 输出结果: 这里通过new方法创建了两个线程,然后使用start()方法来启动线程,两个线程的作用是:两个线程同时从1数到9,并将结果打印出来。 运行上面的程序代码时,可能会在控制台上输出多种不同的结果。从123456789123456789到112233445566778899或121233445566778989在内的各种情况都是可能出现的,输出结果可能与操作系统的调度方式有关。 2、停止线程。当创建一个线程后,可以通过多种属性方法判断该线程是否处于活动状态,启动和停止一个线程等。相关代码及其解释: public class MyAlpha { //下面创建的方法是在线程启动的时候的时候调用 public void Beta() { while(true) { Console.WriteLine("MyAlpha.Beta is running in its own thread."); } } } public class Simple { public static int Stop() { Console.WriteLine("Thread Start/Stop/Join"); MyAlpha TestAlpha=new MyAlpha(); //创建一个线程对象 Thread MyThread=new Thread(new ThreadStart(TestAlpha.Beta)); //开起一个线程 MyThread.Start(); while(!MyThread.IsAlive); Thread.Sleep(1); //停止线程 MyThread.Abort(); //加入一个线程 MyThread.Join(); Console.WriteLine(); Console.WriteLine("TestAlpha.Beta has finished"); //进行异常处理 try { Console.WriteLine("Try to restart the TestAlpha.Beta thread"); MyThread.Start(); } catch(ThreadStateException) { Console.WriteLine("ThreadStateException trying to restart TestAlpha.Beta."); Console.WriteLine("Expected since aborted threads cannot be restarted."); } return 0; } } 输出结果: 3、进程的同步 为了保证数据结构的稳定,必须通过使用锁来调整两个线程的操作顺序。这里通过对引用的对象申请一个锁,一旦一段程序获得该锁的控制权后,就可以保证只有它获得了这个锁并能够对该对象进行操作。同样,利用这种锁,一个线程可以一直处于等待状态,直到有能够唤醒他的信号通过变量传来为止。 相关代码及其解释: public class Monitor1 { public static void Synchronize() { int result=0; //Result initialized to say there is no error Cell cell=new Cell(); CellProd prod=new CellProd(cell,20); CellCons cons=new CellCons(cell,20); Thread producer=new Thread(new ThreadStart(prod.ThreadRun)); Thread consumer=new Thread(new ThreadStart(cons.ThreadRun));