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 }

 此案例执行效果同上

 

posted on 2012-08-05 00:14  bergy  阅读(188)  评论(0编辑  收藏  举报