创建线程之Thread类和线程池

1.Thread类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class myclass
    {
        private string data;
        public myclass(string data)
        {
            this.data = data;
        }
        public void threadmain()
        {
            Console.WriteLine("thread1 is begin and it is data:"+this.data);
            Thread.Sleep(3000);
            Console.WriteLine("thread1 end");
        }
    }
    class Program
    {
            private static void threadmain2()
            {
                Console.WriteLine("thread2 is begin " );
                Thread.Sleep(3000);
                Console.WriteLine("thread2 end");
            }
        static void Main(string[] args)
        {
            //主线程结束后,所有前台线程会依次执行结束,后台线程不会运行
            var mc=new myclass("programming!");
            var t1 = new Thread(mc.threadmain) { Name="mythread1",IsBackground=false};//设置一个名为mythread的线程,且不是后台线程
            t1.Priority = ThreadPriority.Lowest;//设置线程的优先级,ThreadPriority枚举定义一个值包含:Highest,AboveNormal,Normal,BelowNormal,Lowest(优先级从高到低排列)
            t1.Start();      //启动线程
            t1.Join();//在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。等到t1结束才开始调用t2
            var t2 = new Thread(threadmain2) { Name="mythread2"};
            t2.Priority = ThreadPriority.Highest;
            t2.Start();
            //t2.Abort();//停止t2这个线程
            Console.WriteLine("main thread is end!");
        }
    }
}

2.线程池,一般用于时间较短的任务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int workthread;
            int iothread;
            ThreadPool.GetMaxThreads(out workthread, out iothread);//获得该线程池的最大线程数(默认为1023个工作线程和1000个I/O线程)
            Console.WriteLine("max worker threads:{0},max i/o threads:{1}",workthread,iothread);
            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(worejob);//将worejob()方法排入队列以便执行,此方法在有线程池线程变得可用时执行
            }
            Thread.Sleep(30000);
            //线程池中的线程都是后台线程,如果所有前台线程结束,后台线程就会停止
            Console.WriteLine("main thread over");
        }

        private static void worejob(object state)
        {
            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine("loop{0}:running inside in the pool is thread{1}", i, Thread.CurrentThread.ManagedThreadId);//获得当前托管线程的唯一标识符
                Thread.Sleep(1000);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/runninglzw/p/3844198.html