建立線程之Thread類和線程池

1.Thread類ide

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.線程池,通常用於時間較短的任務oop

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);
            }
        }
    }
}
相關文章
相關標籤/搜索