多线程

在一个程序中,这些独立运行的程序片断叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理”。

使用首先引用命名空间

using System.Threading;

线程和进程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈程序计数器为其执行上下文

多线程主要是为了节约CPU时间,发挥利用,根据具体情况而定. 线程的运行中需要使用计算机的内存资源和CPU

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//关闭多线程访问的检查
        }
        Thread th = null;
        private void button1_Click(object sender, EventArgs e)
        {
           th = new Thread(xuanhuan);//实例化一个线程,需要一个委托变量
           th.IsBackground = true;//将线程转化为后台线程
           th.Start();
        }
        public void xuanhuan()
        {
            for (int i = 1; i <= 10;i++ )
            {
                label1.Text = i.ToString();
                Thread.Sleep(1000);//每隔1秒钟
                if(i==5)
                {
                    th.Abort();//终止线程
                }
            }

        }

    }
}

随机抽取电话号码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;//引用线程的命名空间
using System.Windows.Forms;

namespace suijixuanqudianhuahaoma
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//关闭跨线程访问的检查
        }
        Thread th = null;//初始化一个线程变量
        private void button1_Click(object sender, EventArgs e)
        {
            th = new Thread(xuhuan);//调用循环的委托变量的方法
            th.IsBackground = true;//转为后台运行线程
            th.Start();//开始线程
        }

        public void xuhuan()
        {
            //创建号码集合
            List<string> list = new List<string>();
            list.Add("111111111");
            list.Add("222222222");
            list.Add("333333333");
            list.Add("444444444");
            list.Add("555555555");
            list.Add("666666666");
            list.Add("777777777");
            //循环随机显示号码
            while(true)
            {
            Random r = new Random();
            int i=r.Next(0,list.Count);//获取索引的随机数
            label2.Text=list[i];
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            th.Abort();//终止线程
        }



    }
}

 

posted @ 2016-07-03 21:20  枫炎  阅读(275)  评论(0编辑  收藏  举报