关于线程的学习笔记
2010-08-11 15:29
183 查看
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
/*验证线程工作的原理*/
class Program
{
static int count;
static void Main(string[] args)
{
/*主线程实例化*/
Thread thisre = Thread.CurrentThread;
thisre.Name = "Main";
/*实例化输入参数*/
count=int.Parse(Console.ReadLine());
/*实例化工作线程*/
ThreadStart thsta = new ThreadStart(startwork);
Thread th = new Thread(thsta);
th.Name = "worker";
/*设置工作线程的优先级为最高级*/
th.Priority = ThreadPriority.Highest;
/*工作线程开始*/
th.Start();
displaynumber();
Console.WriteLine("main finished");
Console.ReadLine();
}
static void displaynumber()
{
Thread thred = Thread.CurrentThread;
string name = thred.Name;
Console.Write(name+"\r\n");
Console.Write(thred.CurrentCulture+"\r\n");
for (int i = 0; i <= 8 * count; i++)
if (i % count == 0)
Console.Write(name + i.ToString()+"\r\n");
}
static void startwork()
{
displaynumber();
Console.WriteLine("finished");
}
}
}
![](http://images.cnblogs.com/cnblogs_com/huirenxiao/QQ截图未命名.gif)
根据执行结果可以看到,在工作线程优先级设置为最高时,主线程让位于工作线程
2.当多个线程访问同一个变量时,会引起有些线程取到垃圾数据的情况,这时候可以用C#中的lock(X)去解决,称作排他锁或独占锁
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
/*验证线程工作的原理*/
class Program
{
static int count;
static void Main(string[] args)
{
/*主线程实例化*/
Thread thisre = Thread.CurrentThread;
thisre.Name = "Main";
/*实例化输入参数*/
count=int.Parse(Console.ReadLine());
/*实例化工作线程*/
ThreadStart thsta = new ThreadStart(startwork);
Thread th = new Thread(thsta);
th.Name = "worker";
/*设置工作线程的优先级为最高级*/
th.Priority = ThreadPriority.Highest;
/*工作线程开始*/
th.Start();
displaynumber();
Console.WriteLine("main finished");
Console.ReadLine();
}
static void displaynumber()
{
Thread thred = Thread.CurrentThread;
string name = thred.Name;
Console.Write(name+"\r\n");
Console.Write(thred.CurrentCulture+"\r\n");
for (int i = 0; i <= 8 * count; i++)
if (i % count == 0)
Console.Write(name + i.ToString()+"\r\n");
}
static void startwork()
{
displaynumber();
Console.WriteLine("finished");
}
}
}
![](http://images.cnblogs.com/cnblogs_com/huirenxiao/QQ截图未命名.gif)
根据执行结果可以看到,在工作线程优先级设置为最高时,主线程让位于工作线程
2.当多个线程访问同一个变量时,会引起有些线程取到垃圾数据的情况,这时候可以用C#中的lock(X)去解决,称作排他锁或独占锁
相关文章推荐
- 个人学习笔记--关于unity3d开线程后卡死BUG
- 关于线程与进程之间的关系,今天学习了一下,在这做一下笔记。
- 关于线程学习过程的笔记
- 关于php学习笔记二
- 关于Kali进行ARP欺骗的学习笔记
- 关于堆栈的算法...对于july大神的文章的学习笔记
- 【C#】线程学习笔记
- [操作系统学习笔记(2)] 线程的实现
- 关于建站的学习笔记(一)
- 【tcp-ip学习笔记】关于IP协议层、IP地址
- 关于学习ios开发的一些笔记
- ios学习笔记:我的收集——关于UIApplication
- 关于GDI+学习笔记。
- Unity学习笔记 之 关于 Unity UI 的 Slider 的代码记录
- java学习笔记,关于java的一些基础知识,适用于初学者,第一节
- cocos2d-x 3.1.1 学习笔记[17] 关于函数的那些勾当
- 关于多线程学习的笔记
- 学习笔记 -- 关于 STL 中的 heap ( 堆 )
- MSSQL存储过程学习笔记一:关于存储过程
- 关于SQLServer2005的学习笔记(一)——前言