110,539
社区成员
发帖
与我相关
我的任务
分享
private void button1_Click(object sender, EventArgs e) {
new Thread(() => {
lock (m_lst_sync) {
this.Test("Thread");
Thread.Sleep(1000);
Console.WriteLine("Thread End");
}
}) { IsBackground = true }.Start();
Thread.Sleep(10); //先停一下 让线程先执行
this.Test("Thread Main");
}
private void Test(string str) {
Console.WriteLine(str);
}
控制台输出
Thread
Thread Main
The thread '<No Name>' (0x940) has exited with code 0 (0x0).
Thread End
可以看到我在线程里面暂停了1秒也没有影响 其他的调用Test函数
但是代码这样
private List<int> m_lst_sync = new List<int>();
new Thread(() => {
lock (m_lst_sync) {
for (int i = 10; i < 20; i++) {
m_lst_sync.Add(i);
Thread.Sleep(100);
}
}
}) { IsBackground = true }.Start();
new Thread(() => {
lock (m_lst_sync) {
for (int i = 0; i < 10; i++) {
m_lst_sync.Add(i);
Thread.Sleep(100);
}
}
}) { IsBackground = true }.Start();
Thread.Sleep(3000);
m_lst_sync.ForEach(x => Console.WriteLine(x));
控制台的输出只会是 10-19然后0-9 或者 0-9然后10-19(线程的启动顺序也不一定是按照代码的启动顺序来的)
应为当一个线程进入lock的时候 m_lst_sync被锁定 当另一个线程要lock的时候 发现m_lst_sync处于锁定状态 所以他需要等待解锁才能进入 lock 里面 所以要么下面的这个循环等待上面的循环执行完毕 或者上面的等待下面的执行完毕
但是这样写 效果又不一样了
new Thread(() => {
for (int i = 10; i < 20; i++) {
lock (m_lst_sync) {
m_lst_sync.Add(i);
Thread.Sleep(100);
}
}
}) { IsBackground = true }.Start();
new Thread(() => {
for (int i = 0; i < 10; i++) {
lock (m_lst_sync) {
m_lst_sync.Add(i);
Thread.Sleep(100);
}
}
}) { IsBackground = true }.Start();
Thread.Sleep(3000);
m_lst_sync.ForEach(x => Console.WriteLine(x));
//=====输出结果
10
0
11
1
12
2
13
3
14
4
15
5
16
6
17
7
18
8
19
9
一个进入lock 另一个等待 但是添加完毕 sleep完毕 会跳出lock 那么另一个lock就进入了 那么上一个lock二次循环的时候 需要等待 所以就看到了上面的效果 循环被两个占用