多线程进阶代码一

  1. // @ 改造于挽留刀的技术系列文章-C#的多线程机制探索
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. namespace MutiThread
  8. {
  9.     /* 最基本的一个多线程的例子,什么是进程呢?当一个程序开始运行时,
  10.      * 它就是一个进程,进程所指
  11.      * 包括运行中的程序和程序所使用到的内存和系统资源。而一个进程又
  12.      * 是由多个线程所组成的,线程是程序中的一个执行流,每个线程都有
  13.      * 自己的专有寄存器(栈指针、程序计数器等),但代码区是共享的,即
  14.      * 不同的线程可以执行同样的函数。多线程是指程序中包含多个执行流,
  15.      * 即在一个程序中可以同时运行多个不同的线程来执行不同的任务,也
  16.      * 就是说允许单个程序创建多个并行执行的线程来完成各自的任务。微
  17.      * 观上串行,宏观上并行。 */
  18.     /* 多线程的好处在于可以提高CPU的利用率
  19.      * •Start():启动线程
  20.      * •Sleep(int):静态方法,暂停当前线程指定的毫秒数 
  21.      * •Abort():通常使用该方法来终止一个线程 
  22.      * •Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复。
  23.      * •Resume():恢复被Suspend()方法挂起的线程的执行
  24.      * Suspend容易造成死锁,常赋予线程以不同的优先级来代替使用它,线程的优先级
  25.      * 决定了线程能够得到多少CPU时间*/
  26.     class Program
  27.     {
  28.         [STAThread]
  29.         static void Main(string[] args)
  30.         {
  31.             Console.WriteLine("Thread Start/Stop/Join Sample");
  32.             Test test = new Test();
  33.             // 创建线程,ThreadState变为UnStarted
  34.             Thread th1 = new Thread(new ThreadStart(test.Beta));
  35.             Thread th2 = new Thread(new ThreadStart(test.Beta2));
  36.             th1.Name = "Th1";
  37.             th2.Name = "Th2";
  38.             
  39.             // 启动线程,ThreadState变为Running
  40.             th1.Start();
  41.             th2.Start();
  42.             
  43.             while (!th1.IsAlive)
  44.             {
  45.                 // 将主线程挂起指定的时间
  46.                 Thread.Sleep(1);
  47.             }
  48.             // 终止线程th1,不一定立即会终止
  49.              th1.Abort();
  50.             // 阻塞调用线程,直到终止,ThreadState变为Stopped
  51.             th1.Join();
  52.             th2.Abort();
  53.             th2.Join();
  54.             //Console.WriteLine();
  55.             Console.WriteLine("Test.Beta has finished");
  56.             Console.ReadLine();
  57.         }
  58.     }
  59.     class Test
  60.     {
  61.         /// <summary>
  62.         /// 线程中所包含的方法
  63.         /// </summary>
  64.         public void Beta()
  65.         {
  66.             while (true)
  67.             {
  68.                 Console.WriteLine("Test.Beta is running in its own thread.");
  69.             }
  70.         }
  71.         public void Beta2()
  72.         {
  73.             while (true)
  74.             {
  75.                 Console.WriteLine("Test.Beta2 is running in its own thread.");
  76.             }
  77.         }
  78.     }
  79. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值