多线程
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; //线程操作的类在这个命名空间下. namespace C02多线程 { public partial class Form1 : Form { public Form1() { InitializeComponent(); //关闭控件的跨线程访问检查 TextBox.CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { int sum = 0; for (int i = 0; i < 999999999; i++) { sum += i; } MessageBox.Show("ok"); } private void button2_Click(object sender, EventArgs e) { //创建1个线程对象 并为这个线程对象指定要执行的方法. Thread thread = new Thread(TestThread); //设置线程为后台线程. thread.IsBackground = true; //开启线程 thread.Start(); //线程默认情况下都是前台线程. //要所有的前台线程退出以后 程序才会退出. //后台线程 只要所有的前台线程结束 后台线程就会立即结束. //进程里默认的线程我们叫做主线程或者叫做UI线程. //线程什么时候结束 该线程执行的方法执行完以后 线程就自动退出. //多个线程访问同一资源 可能造成不同步的情况. 这个叫做 线程重入. //th.Abort(); 强行停止线程. //Thread.Sleep(1000);//将当前线程暂停 单位毫秒 //Thread.CurrentThread;得到当前线程的引用 //线程调用带参数的方法 //创建1个ParameterizedThreadStart委托对象.为这个委托对象绑定方法. //将委托对象通过构造函数传入线程对象 //启动线程的时候调用Start()的重载 将参数传入. } //准备让线程去调用. private void TestThread() { int sum = 0; for (int i = 0; i < 999999999; i++) { sum += i; } MessageBox.Show("ok"); } private void CountNunm() { //使用lock加锁 请联想你上厕所的情况 lock (this) { for (int i = 0; i < 10000; i++) { int num = int.Parse(textBox1.Text.Trim()); num++; //Thread.Sleep(500);//将当前线程暂停 // Thread.CurrentThread.Abort(); //Thread th = Thread.CurrentThread; //th.Abort(); //if (num == 5000) //{ // th.Abort(); //} textBox1.Text = num.ToString(); } } } Thread th; private void button3_Click(object sender, EventArgs e) { th = new Thread(CountNunm); th.Name = "哈哈线程"; th.IsBackground = true; th.Start(); //Thread th1 = new Thread(CountNunm); //th1.IsBackground = true; //th1.Start(); } private void button4_Click(object sender, EventArgs e) { //ThreadStart s = new ThreadStart(CountNunm); //Thread th = new Thread(CountNunm); ParameterizedThreadStart s = new ParameterizedThreadStart(TestThreadParsms); Thread t = new Thread(s); t.IsBackground = true; t.Start("你好啊"); } private void TestThreadParsms(object obj) { Console.WriteLine(obj.ToString()); } } }