【.NET重修计划】简单线程

  一、简单的线程声明。

  ⒈需要应用命名空间。

 

using System.Threading;

 

  ⒉声明格式:

  Thread  线程名 = new Thread(new  Thread.start(方法名));

 

  二、用lock()方法来限制线程。

 

lock (this)
{

}

 

 

  lock()方法内的内容一次只允许一个线程调用。

 

  三、多线程任务:“用10个线程创建1000个txt文本文档。”

 

代码
1 using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Text;
5  using System.Threading;
6  using System.IO;
7
8  namespace 简单线程
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 //声明Write类。
15   Write write1 = new Write();
16
17 //创建多个线程。
18   Thread thread1 = new Thread(new ThreadStart(write1.WriteText));
19 Thread thread2 = new Thread(new ThreadStart(write1.WriteText));
20 Thread thread3 = new Thread(new ThreadStart(write1.WriteText));
21 Thread thread4 = new Thread(new ThreadStart(write1.WriteText));
22 Thread thread5 = new Thread(new ThreadStart(write1.WriteText));
23 Thread thread6 = new Thread(new ThreadStart(write1.WriteText));
24 Thread thread7 = new Thread(new ThreadStart(write1.WriteText));
25 Thread thread8 = new Thread(new ThreadStart(write1.WriteText));
26 Thread thread9 = new Thread(new ThreadStart(write1.WriteText));
27 Thread thread10 = new Thread(new ThreadStart(write1.WriteText));
28 thread1.Start();
29 thread2.Start();
30 thread3.Start();
31 thread4.Start();
32 thread5.Start();
33 thread6.Start();
34 thread7.Start();
35 thread8.Start();
36 thread9.Start();
37 thread10.Start();
38
39 }
40
41 public class Write
42 {
43 //创建一个累加的方法,其一避免同一个文本名同时创建,其二避免两个线程同时调用创建同一个文本名。
44   int x = 0;
45 public int Num()
46 {
47 x++;
48 return x;
49 //注意:如果直接用return x++;会先返回x,再++。
50   }
51
52 //线程方法。
53   public void WriteText()
54 {
55
56 for (int i = 0; i < 100; i++)
57 {
58 //y获取累加的x。
59 int y = Num();
60
61 //使用File方法需要引用命名空间System.IO。
62 //输入路径时要多输入一个"\",第一个"\"是转译符。
63 //File.WriteAllText(参数1,参数2),参数1为文本名及路径,参数2为文本内容。
64 File.WriteAllText("H:\\Blog_Work\\简单线程\\多线程创建的文件\\" + y + ".txt", "AAAAAA");
65 }
66
67 }
68 }
69 }
70 }
71

 

  Over

 

 

posted @ 2010-11-12 16:02  Lothduin  阅读(164)  评论(0编辑  收藏  举报