线程

来源:互联网 发布:steam免费mac游戏推荐 编辑:程序博客网 时间:2024/06/04 19:54


原文:http://wenwen.soso.com/z/q104059706.htm


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

原创粉丝点击