-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncLockDemo.java
More file actions
71 lines (61 loc) · 1.82 KB
/
Copy pathSyncLockDemo.java
File metadata and controls
71 lines (61 loc) · 1.82 KB
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
package sync;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author : CodeWater
* @create :2022-06-02-22:49
* @Function Description :可重入锁演示
*
*/
//可重入锁
public class SyncLockDemo {
public synchronized void add() {
add();
}
public static void main(String[] args) {
//Lock演示可重入锁
Lock lock = new ReentrantLock();
//创建线程
new Thread(()->{
try {
//上锁
lock.lock();
System.out.println(Thread.currentThread().getName()+" 外层");
try {
//上锁
lock.lock();
System.out.println(Thread.currentThread().getName()+" 内层");
}finally {
//释放锁
lock.unlock();
}
}finally {
//释放做
lock.unlock();
}
},"t1").start();
//创建新线程
new Thread(()->{
lock.lock();
System.out.println("aaaa");
lock.unlock();
},"aa").start();
// new SyncLockDemo().add(); //递归锁演示
// synchronized //可重入锁演示
// Object o = new Object();
// new Thread(()->{
// synchronized(o) {
// System.out.println(Thread.currentThread().getName()+" 外层");
//
// synchronized (o) {
// System.out.println(Thread.currentThread().getName()+" 中层");
//
// synchronized (o) {
// System.out.println(Thread.currentThread().getName()+" 内层");
// }
// }
// }
//
// },"t1").start();
}
}