A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sunrise2 高级黑马   /  2014-7-22 08:14  /  681 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一.线程的优点

1.服务器 一般负载的情况下 线程可以提高效率;
2.使用线程执行的代码出现故障不会影响主程序,提高程序稳定和可靠性。

二.线程的创建及其常用属性

1.线程创建
  1. ThreadStart ts1 = new ThreadStart(function2);//线程定义 执行                                       

  2. Thread t1 = new Thread(ts1);

  3. t1.Start();
复制代码

或者
  1. Thread t1=new Thread(new ThreadStart(function2));  

  2. t1.Start();
复制代码

2.线程常用属性
  1. Priority 获取或设置,线程优先级

  2. IsBackgroud 获取或设置,是否为后台线程

  3. Abort() :终止线程

  4. Start() 开始线程
复制代码

三.程序实例
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;

  6. namespace Thread2
  7. {
  8.     class Program
  9.     {
  10.         static void function1()
  11.         {
  12.             for (int i = 0; i < 40; i++)
  13.             {
  14.                 Console.WriteLine(i);
  15.             }
  16.         }
  17.         static void function2()
  18.         {
  19.             for (int i = 41; i <200; i++)
  20.             {
  21.                
  22.                 Console.WriteLine(i);
  23.                 int c = 2;
  24.                 int x = 0;
  25.                 int y = c / x;
  26.             }
  27.         }
  28.         static void function3()
  29.         {
  30.             for (int i = 200; i < 205; i++)
  31.             {
  32.                 Console.WriteLine(i);
  33.                 //int c = 2;
  34.                 //int x = 0;
  35.                 //int y = c / x;

  36.             }
  37.         }
  38.         static void Main(string[] args)
  39.         {
  40.             Console.WriteLine("Main begin !");

  41.             ThreadStart ts = new ThreadStart(function1);//线程定义 执行
  42.             Thread t = new Thread(ts);
  43.             t.Priority = ThreadPriority.Highest;
  44.             t.Start();

  45.             Console.WriteLine("Main end!");

  46.             ThreadStart ts1 = new ThreadStart(function2);//线程定义 执行
  47.             Thread t1 = new Thread(ts1);
  48.             //t1.Priority = ThreadPriority.Highest;
  49.             //t1.IsBackground = true;//没执行完 主程序也退出
  50.             t1.Start();

  51.             function3();//直接执行

  52.             Console.WriteLine("Main1111 end!");
  53.         }

  54.     }
  55. }
复制代码



0 个回复

您需要登录后才可以回帖 登录 | 加入黑马