【.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

 

 

转载于:https://www.cnblogs.com/firstdown/archive/2010/11/12/1875773.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值