首页 > 代码库 > 多线程

多线程

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

namespace 多线程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//关闭线程检查
TextBox.CheckForIllegalCrossThreadCalls = false;

//只有当所有的前台线程执行完毕程序才会退出
//如果前台线程退出后台线程不管有没有执行完也会跟着退出
//Thread.Sleep(1000);//让线程暂停,单位是毫秒
//Thread.CurrentThread;//等到当前线程的引用
//new Thread().Abort();//强行停止当前线程
}

private void Test()
{
lock(this)//this代表当前对象
{
for (int i = 0; i < 1000; i++)
{
int num = int.Parse(textBox1.Text);
num++;
textBox1.Text = num.ToString();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(Test);
th1.IsBackground=true;
th1.Start();

Thread th2 = new Thread(Test);
th2.IsBackground = true;
th2.Start();
}
}
}