C#多线程实例

来源:互联网 发布:mac电脑怎么打出顿号 编辑:程序博客网 时间:2024/06/07 06:08
Thread th=new Thread(new ThreadStart(方法));th.Name="aa" 为线程命名th.Priority=ThreadPriority.Highest 最高  //运行的优先级                               .Normal 缺省                               .Lowest 最底th.Start();lock(对象){       //代码 保证一个线程执行完这段代码之后另外       //一个线才执行这段代码,线程有序       }Start();Sleep(毫秒数);  //休眠,这个毫秒等待完成后自动继续执行Suspend();   //挂起,不自动恢复Resume();    //通过Resume去恢复一个挂起的线程Abort();     //停止当前线程示例:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;  //命名空间namespace WindowsApplication19{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        Thread th1;        Thread th2;        Thread th3;        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            //关闭线程            th1.Abort();            th2.Abort();            th3.Abort();          }        private void button1_Click(object sender, EventArgs e)        {            th1 = new Thread(new ThreadStart(Run1));  //固定写法            th2 = new Thread(new ThreadStart(Run2));            th3 = new Thread(new ThreadStart(Run3));            th1.Priority = ThreadPriority.Highest;  //设置优先级            th2.Priority = ThreadPriority.AboveNormal;            th3.Priority = ThreadPriority.Normal;            th1.Name = "aa";  //设置名字            th2.Name = "bb";            th3.Name = "cc";            th1.Start();  //启动线程            th2.Start();            th3.Start();        }        private void Run1()        {            for (int i = 0; i < 100; i++)            {                this.progressBar1.Value = i;                Thread.Sleep(100);            }        }        private void Run2()        {            for (int i = 0; i < 100; i++)            {                this.progressBar2.Value = i;                Thread.Sleep(100);            }        }        private void Run3()        {            for (int i = 0; i < 100; i++)            {                this.progressBar3.Value = i;                Thread.Sleep(100);            }        }    }}