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
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading;
namespace
ThreadTest0902
{
public
class
Program
{
bool
bl =
false
;
static
void
Main(
string
[] args)
{
Program p =
new
Program();
Thread thread =
new
Thread(p.Print);
thread.Start();
p.Print();
Console.ReadKey();
}
public
void
Print()
{
if
(!bl)
{
Console.WriteLine(
"I'm False"
);
bl =
true
;
}
}
}
}
|
执行后你会发现,有时候打印一次,有时候会打印两次
其实大家也能猜到是什么原因了,在第一个线程打印时,bl还是false,另一个线程进判断语句了,于是也进来打印了
为了避免这样无法预知的结果,于是我们就想着,在第一个线程(线程A)进行操作上,把门关上,锁起来,另一个线程(线程B)只能在外面等着,等线程A处理好了,出去了,才可以让线程B进来
于是微软爸爸就给了我们把万能锁(lock)
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
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading;
namespace
ThreadTest0902
{
public
class
Program
{
bool
bl =
false
;
static
readonly
object
locker =
new
object
();
static
void
Main(
string
[] args)
{
Program p =
new
Program();
Thread thread =
new
Thread(p.Print);
thread.Start();
p.Print();
Console.ReadKey();
}
public
void
Print()
{
lock
(locker)
{
if
(!bl)
{
Console.WriteLine(
"I'm False"
);
bl =
true
;
}
}
}
}
}
|
单独把这个拿出来说下
static object locker = new object();
一开始我只是写成object locker = new object();
后来看了网上的代码,看了下,基本上都是private static readonly于是我就客串下百度
private:如果该实例是public,那么无关的代码也可能会锁定该对象,那就会出现多个线程等待同一个对象释放,导致死锁
static:同上,如果是公共数据类型也会出现上述问题
readonly:一旦在lock中对象值变了,那么其他线程就可以进来执行了,因为互斥锁的对象变了