forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT12.java
More file actions
51 lines (40 loc) · 1.01 KB
/
T12.java
File metadata and controls
51 lines (40 loc) · 1.01 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
package com.basic;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program JavaBooks
* @description: ReentrantLock
* @author: mf
* @create: 2019/12/30 19:51
*/
public class T12 {
Lock lock = new ReentrantLock();
void m1() {
try {
lock.lock(); // 加锁
for (int i = 0; i < 10; i++) {
System.out.println(i);
TimeUnit.SECONDS.sleep(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void m2() {
lock.lock();
System.out.println("m2...");
}
public static void main(String[] args) {
T12 t12 = new T12();
new Thread(t12::m1, "t1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(t12::m2, "t2").start();
}
}