多线程学习三、深入理解代码

多线程的深入理解的示例代码

using System;
using System.Threading;

namespace ThreadDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Thread thread = new Thread(ThreadOne);
            //默认是前台线程,全部执行完才会关闭

            //thread.IsBackground = true;//将该线程设置为后台线程,前台结束,不考虑后台是否结束了
            thread.Priority = ThreadPriority.Highest;//将线程的优先级设置为最高,但是并不绝对

            thread.Start();
            thread.Abort();//直接结束线程,无论是否执行完毕,建议不要使用
            Console.WriteLine("获取主线程ID" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("获取子线程ID" + thread.ManagedThreadId);
            thread.Join();//等子线程执行完以后才能继续执行,join(1000),表示等待时间
             //有参数的线程用new ParameterizedThreadStart
            Thread thread1 = new Thread(new ParameterizedThreadStart(ThreadOne));
            //在start的时候传入参数,如果多个参数的或就传入List集合进去或者数组,然后在方法内进行处理
            thread1.Start("1212");
        }

        static void ThreadOne()
        {
            Thread.Sleep(1000);//延迟一秒后执行
            Console.WriteLine("子线程输出");
        }
        //有参的的方法传入的参数类型必须是object
        static void ThreadTwo(object obj)
        {
            Console.WriteLine(obj.ToString());
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/q1923408717/article/details/107917523