您的位置:首页 > 其它

关于线程的学习笔记

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");
}
}
}


根据执行结果可以看到,在工作线程优先级设置为最高时,主线程让位于工作线程

2.当多个线程访问同一个变量时,会引起有些线程取到垃圾数据的情况,这时候可以用C#中的lock(X)去解决,称作排他锁或独占锁
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: