技术开发 频道

自学.NET之路-多线程


【IT168技术文档】

  命名空间:
  System.Threading
  创建线程:
  Thread 线程实例的名称 = new Thread(new ThreadStart(方法名称));
  调用Thread实例的Start()方法才能使线程开始执行.
class Test { static void Main(string[] args) { Test obj = new Test(); //实例化 Thread.CurrentThread.Name = "主线程"; //主程序进程命名为主线程 Thread objThread = new Thread(new ThreadStart(obj.ActionMethod)); //创建子线程 objThread.Name = "子线程"; objThread.Start(); //启动子线程 obj.ActionMethod(); } void ActionMethod() { for (int count = 1; count <= 10; count++) { Console.WriteLine("线程名:" + Thread.CurrentThread.Name); } } }
  执行的顺序无法预测,因为它取决于处理器

  C#中通过lock关键字提供同步.锁定机制确保每次只有一个线程访问方法或代码.除非它已经完成了对方法或代码的执行,否则其他线程就无法进行访问.当两个或两个以上的线程试图访问一个共享资源或共享文件时,这种机制就尤其有用.
class Test { static void Main(string[] args) { Test obj = new Test(); Thread.CurrentThread.Name = "主线程"; Thread objThread = new Thread(new ThreadStart(obj.ActionMethod)); objThread.Name = "子线程"; objThread.Start(); obj.ActionMethod(); } void ActionMethod() { lock (this) { for (int count = 1; count <= 10; count++) { Console.WriteLine("线程名:" + Thread.CurrentThread.Name); } } } }
0
相关文章