using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;namespace 线程 { class Program { static void Main(string[] args) { Program p = new Program(); //创建线程,委托一个方法 Thread t = new Thread(new ThreadStart(p.ThreadProc)); t.Name = "子线程"; //设置线程名 Thread.CurrentThread.Name = "主线程"; Console.WriteLine("主线程启动:"); //启动线程方法 p.ThreadProc(); t.Start();
还有就是,,程序默认线程,和自定义线程的执行优先级问题,,让我很困惑,,如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace 线程
{
class Program
{
static void Main(string[] args)
{ Program p = new Program();
//创建线程,委托一个方法
Thread t = new Thread(new ThreadStart(p.ThreadProc));
t.Name = "子线程";
//设置线程名
Thread.CurrentThread.Name = "主线程";
Console.WriteLine("主线程启动:"); //启动线程方法
p.ThreadProc();
t.Start();
Console.Read();
} public void ThreadProc()
{
lock (this)
{
for (int i = 0; i < 2; i++)
{
Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, i);
}
} }
}
}
打印的是:
主线程启动:
主线程: 0
主线程: 1
子线程: 0
子线程: 1 即使把 p.ThreadProc();
t.Start();
改成 t.Start();
p.ThreadProc(); 执行结果还是一样...
另一种是我去掉lock(this)这一句..
那如果 t.start()在上面的话就先打出子线程...
反之 p.ThreadProc()就先打出主线程; 是不是锁定了以后,,,线程就都从默认线程开始执行叱..?
当你的程序运行是有个主线程,也就是你的main()函数运行在主线程,
main()函数执行完,跳出main()函数,也就是主线程也运行完了,程序退出。在main()函数中,可以创建其它的线程,
例如主线程叫做threadA,后创建的线程叫做threadB,
两个线程交替运行,threadA运行一个时间段,然后threadB运行一个时间段,
如果主线程threadA运行结束,会强制其它线程结束运行。反之,
其它线程运行结束,主线程不受影响,继续运行!这是基本的过程,
其实这里面会有很多问题,需要仔细看看资料,例如线程互斥,同步,
子线程调用主线程界面元素等等!!!祝你早日理解!
,原来是这样 ,那么threadA和threadB哪一个先运行是取决于代码吗?
是否用了lock线程就先从默认线程开始执行呢?
>>
不是
操作系统调度决定。是否用了lock线程就先从默认线程开始执行呢?
>>
lock是指在同一个时间片中,只允许1个线程访问ThreadProc。有点像Critical_Section.