- // @ 改造于挽留刀的技术系列文章-C#的多线程机制探索
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace MutiThread
- {
- /* 最基本的一个多线程的例子,什么是进程呢?当一个程序开始运行时,
- * 它就是一个进程,进程所指
- * 包括运行中的程序和程序所使用到的内存和系统资源。而一个进程又
- * 是由多个线程所组成的,线程是程序中的一个执行流,每个线程都有
- * 自己的专有寄存器(栈指针、程序计数器等),但代码区是共享的,即
- * 不同的线程可以执行同样的函数。多线程是指程序中包含多个执行流,
- * 即在一个程序中可以同时运行多个不同的线程来执行不同的任务,也
- * 就是说允许单个程序创建多个并行执行的线程来完成各自的任务。微
- * 观上串行,宏观上并行。 */
- /* 多线程的好处在于可以提高CPU的利用率
- * •Start():启动线程
- * •Sleep(int):静态方法,暂停当前线程指定的毫秒数
- * •Abort():通常使用该方法来终止一个线程
- * •Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复。
- * •Resume():恢复被Suspend()方法挂起的线程的执行
- * Suspend容易造成死锁,常赋予线程以不同的优先级来代替使用它,线程的优先级
- * 决定了线程能够得到多少CPU时间*/
- class Program
- {
- [STAThread]
- static void Main(string[] args)
- {
- Console.WriteLine("Thread Start/Stop/Join Sample");
- Test test = new Test();
- // 创建线程,ThreadState变为UnStarted
- Thread th1 = new Thread(new ThreadStart(test.Beta));
- Thread th2 = new Thread(new ThreadStart(test.Beta2));
- th1.Name = "Th1";
- th2.Name = "Th2";
- // 启动线程,ThreadState变为Running
- th1.Start();
- th2.Start();
- while (!th1.IsAlive)
- {
- // 将主线程挂起指定的时间
- Thread.Sleep(1);
- }
- // 终止线程th1,不一定立即会终止
- th1.Abort();
- // 阻塞调用线程,直到终止,ThreadState变为Stopped
- th1.Join();
- th2.Abort();
- th2.Join();
- //Console.WriteLine();
- Console.WriteLine("Test.Beta has finished");
- Console.ReadLine();
- }
- }
- class Test
- {
- /// <summary>
- /// 线程中所包含的方法
- /// </summary>
- public void Beta()
- {
- while (true)
- {
- Console.WriteLine("Test.Beta is running in its own thread.");
- }
- }
- public void Beta2()
- {
- while (true)
- {
- Console.WriteLine("Test.Beta2 is running in its own thread.");
- }
- }
- }
- }
多线程进阶代码一
最新推荐文章于 2023-07-06 13:57:28 发布