C#多線程的簡單例子


 

 

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

namespace ConsoleApplication2
{

     class program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("開始一個新的線程,名為次線程");
            Thread t = new Thread(new ThreadStart(ThreadProc));
            t.Start();
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("主線程:" + i);
                Thread.Sleep(1000);
            }
            Console.WriteLine("調用Join函數等待次線程結束");
            //當次線程執行完畢后,Join阻塞調用線程,直到某個線程終止為止,本例為次線程
           t.Join();
            Console.WriteLine("線程執行完畢");
        }
        public static void ThreadProc()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadPorc:{0}", i);
                Thread.Sleep(1000);//將當前進程阻塞指定的毫秒數
            }
        }
       
    }
}

 

 

static void Main(string[] args)
{
   Thread t1 = new Thread(new ThreadStart(Thread1));
   Thread t2 = new Thread(new ThreadStart(Thread2));

   t1.Priority = ThreadPriority.BelowNormal ;
   t2.Priority = ThreadPriority.Lowest ;
           t1.Start();
      t2.Start();
   }
public static void Thread1()
{ 
   for (int i = 1; i < 1000; i++) 
   {//每運行一個循環就寫一個“1”
     dosth();
    Console.Write("1");
   }
   }
public static void Thread2()
{ 
   for (int i = 0; i < 1000; i++) 
   {//每運行一個循環就寫一個“2”
    dosth();
    Console.Write("2");
   }
}
public static void dosth()
{//用來模擬復雜運算
   for (int j = 0; j < 10000000; j++) 
   {    
    int a=15;
    a = a*a*a*a;
   }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM