简单多线程简单多线程View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //创建一个线程
14             Thread thread = new Thread(Test);
15             //线程处于就需状态,但还没有执行
16             thread.Start();
17             for (int i = 0; i < 100; i++)
18             {
19                 //当前线程休息500毫秒。当阻塞结束后处于就需状态,等待CPU处理
20                 Thread.Sleep(500);
21                 Console.WriteLine("主线程" + i);
22             }
23         }
24     //静态方法
25         static void Test()
26         {
27             for (int i = 0; i < 100; i++)
28             {
29                 //当前线程休息1000毫秒。
30                 Thread.Sleep(1000);
31                 Console.WriteLine("这是子线程" + i);
32             }
33         }
34     }
35 }

 

简单多线程

主线程打印循环数和子线程打印循环数同时执行,交替打印。

简单多线程

由于主线程阻塞时间短,先执行完毕,最后单执行子线程的循环数打印

简单多线程

 

创建子线程时可以如上例传入静态方法:一 Thread thread = new Thread(Test);…… static void Test()……,还可以传入成员方法:二 Thread thread = new Thread(new ThreadA().Test);…… public class ThreadA{ ……public void Test()……}具体如下例:

简单多线程简单多线程View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //创建一个线程
14             Thread thread = new Thread(new ThreadA().Test);
15             //线程处于就需状态,但还没有执行
16             thread.Start();
17             for (int i = 0; i < 100; i++)
18             {
19                 //当前线程休息500毫秒。当阻塞结束后处于就需状态,等待CPU处理
20                 Thread.Sleep(500);
21                 Console.WriteLine("主线程" + i);
22             }
23         }
24     }
25     public class ThreadA
26     {
27         //成员方法
28         public void Test()
29         {
30             for (int i = 0; i < 100; i++)
31             {
32                 //当前线程休息1000毫秒。
33                 Thread.Sleep(1000);
34                 Console.WriteLine("这是子线程" + i);
35             }
36         }
37     }
38 }

 此案例执行效果同上

 

转载于:https://www.cnblogs.com/yunqinglin/archive/2012/08/05/2623521.html

相关文章:

  • 2018-09-25
  • 2021-12-14
  • 2021-10-19
  • 2021-10-01
  • 2022-01-15
  • 2022-02-11
  • 2022-02-05
猜你喜欢
  • 2021-09-05
  • 2021-09-25
  • 2022-12-23
  • 2021-10-19
  • 2021-11-28
  • 2021-01-04
相关资源
相似解决方案