ThreadSafe-1-同步关键字和ReentrantLock
What is synchronized?
How to understand it?
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
| public class ThreadSafeSample {
public int sharedState;
public void nonSafeAction() {
System.err.println("非线程安全");
while (sharedState < 100000) {
int former = sharedState++;
int latter = sharedState;
if (former != latter - 1) {
System.out.println("Observed data race, former is " + former + ", "
+ "latter is " + latter);
}
}
}
public void safeActionWithSync()
{
//class为锁,或者当前的this为锁
synchronized (ThreadSafeSample.class)
{
System.err.println("同步关键字");
while (sharedState < 100000) {
int former = sharedState++;
int latter = sharedState;
if (former != latter - 1) {
System.out.println("Observed data race, former is " + former + ", "
+ "latter is " + latter);
}
}
}
}
public static void main(String[] args) throws InterruptedException {
ThreadSafeSample sample = new ThreadSafeSample();
Thread threadA = new Thread() {
public void run() {
sample.nonSafeAction();
}
};
Thread threadB = new Thread() {
public void run() {
sample.nonSafeAction();
}
};
threadA.start();
threadB.start();
threadA.join();
threadB.join();
System.out.println("---------------------------------分割线");
sample.sharedState=0;
threadA =new Thread(()->{
sample.safeActionWithSync();
});
threadB =new Thread(()->{
sample.safeActionWithSync();
});
threadA.start();
threadB.start();
threadA.join();
threadB.join();
}
|
Monitor
同步关键字的底层实现,在并发模型中一般翻译成管程;
ReentrantLock
Java 1.5中Doug Lea提出的JDK新实现的可重入锁,内部基于AQS,而AQS又基于CAS;
区别
两者的共同点是
- 协调多线程对共享对象和共享变量的访问
- 可重入,同一线程可以多次获得同一个锁
- 都保证了可见性和互斥性,通过happens-before原则
不同点
ReentrantLock
显示获得、释放锁,synchronized
隐式获得释放锁ReentrantLock
可响应中断、可轮回,synchronized
是不可以响应中断的,为处理锁的不可用性提供了更高的灵活性ReentrantLock
是API
级别的,synchronized
是JVM
级别的,换句话说是直接操作管程的;ReentrantLock
可以实现公平锁,synchronized是非公平的;ReentrantLock
通过Condition
可以绑定多个条件底层实现不一样, synchronized是同步阻塞,使用的是悲观并发策略,lock是同步非阻塞,采用的是乐观并发策略
这部分对于乐观和悲观的理解我觉得是存在歧义的;