一.線程的優(yōu)點(diǎn)
1.服務(wù)器一般負(fù)載的情況下線程可以提高效率;
2.使用線程執(zhí)行的代碼出現(xiàn)故障不會(huì)影響主程序,提高程序穩(wěn)定和可靠性。
二.線程的創(chuàng)建及其常用屬性
1.線程創(chuàng)建
ThreadStartts1=newThreadStart(function2);//線程定義執(zhí)行
Threadt1=newThread(ts1);
t1.Start();
或者
Threadt1=newThread(newThreadStart(function2));
t1.Start();
2.線程常用屬性
PRiority獲取或設(shè)置,線程優(yōu)先級
IsBackgroud獲取或設(shè)置,是否為后臺線程
Abort():終止線程
Start()開始線程
三.程序?qū)嵗?/strong>
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace Thread2{ class Program { static void function1() { for (int i = 0; i < 40; i++) { Console.WriteLine(i); } } static void function2() { for (int i = 41; i <200; i++) { Console.WriteLine(i); int c = 2; int x = 0; int y = c / x; } } static void function3() { for (int i = 200; i < 205; i++) { Console.WriteLine(i); //int c = 2; //int x = 0; //int y = c / x; } } static void Main(string[] args) { Console.WriteLine("Main begin !"); ThreadStart ts = new ThreadStart(function1);//線程定義 執(zhí)行 Thread t = new Thread(ts); t.Priority = ThreadPriority.Highest; t.Start(); Console.WriteLine("Main end!"); ThreadStart ts1 = new ThreadStart(function2);//線程定義 執(zhí)行 Thread t1 = new Thread(ts1); //t1.Priority = ThreadPriority.Highest; //t1.IsBackground = true;//沒執(zhí)行完 主程序也退出 t1.Start(); function3();//直接執(zhí)行 Console.WriteLine("Main1111 end!"); } }}
新聞熱點(diǎn)
疑難解答
圖片精選