1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
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());
}
}
} |