多线程

Threads are responsible for multitasking within a single application.You may never need to manage threads explicitly,because the CLR abstracts much of the thread support into classes that simplify most threading tasks.Even if you don`t  create your own threads explicitly,you`ll ensure that your code can handle multiple threads if it`s run in a multithreading environment.The concern is especially important if you are creating components that mught be used by other programmers in a program that supports multithreading.It is particularly significant to remoting and web services developers.Although web services have many attributes of desktop applications,they are run on the server ,generally lack a user interface ,and force the developer to think about server-side issues such as efficiency and multithreading.

 

1.创建线程

CLR定义了ThreadStart委托,public delegate void ThreadStart();看代码

以前我看见过一些代码,有的要求必须主线程结束之后,新创建的线程才能结束,但是在这里,很明显主线程应该早已结束,但是为什么新创建的线程还能继续运行呢?原来线程分为前台线程和后台线程。这两种线程的区别是:当前台程序全部结束时,程序结束。此时不管后台程序有没有完毕,通通结束,也就是说前台线程是决定程序结束的关键,后台线程没有决定权,当前台线程通通结束时,他们就得结束。 通过IsBackground属性可以查看或者设置线程的前后台情况。我们通过Thread创建的线程默认情况下是前台的,所以程序会等我们的线程通通运行结束才会结束,但是下面的例子就不行了,你会发现新创建的线程根本没有运行:因为通过BeginInvoke调用的线程都是后台线程,前台线程main一结束,整个程序就结束了。

2.关于Join-直到join的线程运行结束才往下运行.例如下面的例子,开始是main和DoTest中的thread并行运行,当beforemain运行结束后,Join的线程把main挂起,自己和thread并行运行,直到自己运行结束,main才继续得以运行。这相当于是一个插队,暂时取代别人把自己当做和外面线程并行运行的代表。

3.终止线程-这里的join是为了不想主函数的writeline在线程结束之前运行。

4.同步-看如下代码

使用Interlocked,还是不对

问题慢慢分析吧。。

这里我有一个疑问?

int temp = (a+1);是有几条语句

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值