C#多线程实例

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);
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值