net 多线程学习 01 单独启动一个线程

new Thread 参数为方法

一个线程 分配 1M的堆栈空间,

PS:

  1. 在CLR的线程操作,包括线程同步,大多都是调用底层的win32 函数 ,用户模式的参数需要传递到内核模式
  2. 进程启动的时候,默认会有三个应用程序域。system domain, shared domain[int,long....] ,domain1; 开启一个thread,销毁一个thread 都会通知进程中的dll,attach,detach 标志位,通知dll的目的就是 给thread做准备工作,比如销毁,让这些dll做资源清理
  3. 时间片切换,8个逻辑处理器,可供8个thread并行执行,比如说9个thread并发执行。 必然会有一个thread休眠30ms

public static void Main()
{
		//initialize a thread class object 
		//And pass your custom method name to the constructor parameter
		Thread t = new Thread(SomeMethod);
		
		//设置线程的名称
		t.Name = "My Parallel Thread";
		//设置线程的优先级
		t.Priority = ThreadPriority.BelowNormal;
		//设置线程为后台线程
		t.IsBackground = true;

		//start running your thread
		t.Start();
		
		//可以用这种方式给线程入参
		//t.Start("Hello World!");

		//while thread is running in parallel you can carry out other operations here

		//wait until Thread "t" is done with its execution.
		//这里会执行另外的线程知道它结束
		t.Join();

		Console.WriteLine("Press Enter to terminate!");
		Console.ReadLine();
}

private static void SomeMethod()
{
		//your code here that you want to run parallel
		//most of the time it will be a CPU bound operation

		// a 是这个线程内的变量,只能在这个线程内被使用
		var a = 1;
		Console.WriteLine("Hello World!");
}

以一个单独的线程启动一个类的方法


public class Example
{
    public static void Main()
    {
        Person person = new Person();

        //initialize a thread class object 
        //And pass your custom method name to the constructor parameter
        Thread t = new Thread(person.Speak);

        //start running your thread
        //dont forget to pass your parameter for the Speak method in Thread's Start method below
        t.Start("Hello World!");

        //wait until Thread "t" is done with its execution.
        t.Join();

        Console.WriteLine("Press Enter to terminate!");
        Console.ReadLine();
    }
}

public class Person
{
    public void Speak(object s)
    {
        //your code here that you want to run parallel
        //most of the time it will be a CPU bound operation

        string say = s as string;
        Console.WriteLine(say);

    }
}

new Thread(new ThreadStart 来单独启动一个线程

Thread t = new Thread(new ThreadStart(() =>
{
		Thread.Sleep(5000);
		Console.WriteLine("子线程执行结束");
}));
t.Start(); 
t.Join(); //在此处等待子线程执行完
Console.WriteLine("主线程执行结束");


作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1